简体   繁体   English

从JavaScript对象中获取数组

[英]Getting Array out of JavaScript Object

I try to get messages from a Server via Websocket and this works so far. 我尝试通过Websocket从服务器获取消息,到目前为止,该方法仍然有效。 I get back an Javascript Object and want to filter out the data I need to put it into the state of my react app. 我取回一个Javascript对象,并想过滤掉我需要将其放入我的应用程序状态的数据。

this is the code im using at the moment: 这是即时通讯目前使用的代码:

connection.onmessage = function (newMessage) {

        if(newMessage.data == '{"msg":"ping"}' ){
            connection.send('{"msg": "pong"}')
        }

        newMessage = JSON.parse(newMessage.data)
        console.log(newMessage.fields)       
    }

and this is the object I get back: 这是我得到的对象:

Javascript Object Javascript对象

I need the Array at args/0 how do i get it? 我需要在args / 0的数组如何获取它?

Thank You 谢谢

you can access the 'args' data in the json object like 'newMessage.args' 您可以像“ newMessage.args”一样访问json对象中的“ args”数据

 var newMessage = {eventName: 'aname', args: ['data1','data2'] } document.getElementById('output').innerHTML = newMessage.args 
 <div id='output'></div> 

It's probably not a good idea to rewrite newMessage in your connection.onmessage function, and may be add more logs when you get a new message. connection.onmessage函数中重写newMessage可能不是一个好主意,并且在收到新消息时可能会添加更多日志。 Can you try this version ? 你可以试试这个版本吗?

connection.onmessage = function (newMessage) {
    console.log("Received new message :", newMessage.data);

    if(newMessage.data == '{"msg":"ping"}' ){
        connection.send('{"msg": "pong"}')
    }

    var parsedMessage = JSON.parse(newMessage.data);

    if (parsedMessage.msg === "changed") {
        console.log("Received changed message :", parsedMessage.fields.args); 
    }
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM