2016-07-28 1636 views
-4

正試圖發送一些靜態數據到websocket並接收相同的內容。該數據是如何在javascript中將[object Object],[object Object]轉換爲[Object,Object]?

var details= 
    [ 
     { 
     "_id": "5799fac61ee480492224071a", 
     "index": 0, 
     "age": 25, 
     "name": "Jean Pierce", 
     "gender": "female", 
     "email": "[email protected]" 
     }, 
     { 
     "_id": "5799fac678aae9a71af63ef2", 
     "index": 1, 
     "age": 23, 
     "name": "Laurie Lopez", 
     "gender": "female", 
     "email": "[email protected]" 
     }, 
     { 
     "_id": "5799fac6c237d929693c08d7", 
     "index": 2, 
     "age": 21, 
     "name": "Padilla Barrett", 
     "gender": "male", 
     "email": "[email protected]" 
     } 
    ]; 

當接收到上述數據時,它是在字符串的形式,所以使用JSON.parse(data),並將其存儲在局部變量它解析以JSON。現在,這裏的問題是,對於解析,它需要轉換爲[Object,Object]表單而不是[object Object],[object Object]這是在控制檯上。如何實現這一目標?

更新:代碼同樣如下,請檢查。

使用下面的代碼

if (client.readyState === client.OPEN) {    
        client.send(JSON.stringify(details));     
       } 

在接收端的數據將數據發送到的WebSocket服務器被接收爲 -

client.onmessage = function(e) { 
     console.log(" Fetched data :"+JSON.parse(e.data)); 
      this.setState({ val: JSON.parse(e.data) 
        }); 
      }.bind(this); 

在第二語句console.log()是示出其結果作爲[object Object],[object Object]但用於解析相同的反應[ Object Object]是必要的。如何實現這一目標?

Console image

+1

「我解析爲JSON」 - **從**不到。 – Quentin

+0

你確定你的控制檯不只是顯示一個對象數組嗎? – gcampbell

+0

我不知道你在問什麼。你似乎是字符串化的(儘管你沒有提供[MCVE])一個對象數組,所以''[object object],[object Object]「將是預期的但不是非常有用的結果。我不明白''[object object]「如何更有用。 – Quentin

回答

-1

在這裏你去:

console.log('[' + array.fill('Object').toString() + ']') 

測試:

var array = [ 
 
    { 
 
    "_id": "5799fac61ee480492224071a", 
 
    "index": 0, 
 
    "age": 25, 
 
    "name": "Jean Pierce", 
 
    "gender": "female", 
 
    "email": "[email protected]" 
 
    }, 
 
    { 
 
    "_id": "5799fac678aae9a71af63ef2", 
 
    "index": 1, 
 
    "age": 23, 
 
    "name": "Laurie Lopez", 
 
    "gender": "female", 
 
    "email": "[email protected]" 
 
    }, 
 
    { 
 
    "_id": "5799fac6c237d929693c08d7", 
 
    "index": 2, 
 
    "age": 21, 
 
    "name": "Padilla Barrett", 
 
    "gender": "male", 
 
    "email": "[email protected]" 
 
    } 
 
] 
 

 
console.log('[' + array.fill('Object').toString() + ']')

雖然老實說,我不知道爲什麼你要這樣過其他 - 兩者同樣(不)有幫助。你確定你不想要console.dir

+0

已更新該問題。請檢查我爲什麼試圖達到同樣的目的。而且,它不用於控制檯,而是用於分配值。 – Worker

+0

老實說你的問題還不是很清楚。我*正在做你所要求的:「它需要轉換爲'[Object,Object]'形式,而不是'[object Object],[object Object]'」。相反,讓我們將我的答案想象爲一個函數。作爲一個例子,請解釋給定輸入的輸出應該是什麼樣的,所以我可以做出更好的答案。 – towerofnix

相關問題