2016-07-28 1638 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

相关问题