Javascript loop through object array?

后端 未结 9 2156
执念已碎
执念已碎 2020-11-28 04:55

I am trying to loop through the following:

{
    \"messages\": [{
        \"msgFrom\": \"13223821242\",
        \"msgBody\": \"Hi there\"
    }, {
        \"         


        
9条回答
  •  长情又很酷
    2020-11-28 05:40

    It appears you may just have missed the "messages" property in the data, so the loop is likely iterating the root Object rather than the Array:

    for (var key in data.messages) {
        var obj = data.messages[key];
        // ...
    }
    

    Unless data was set to messages before the given snippet.

    Though, you should consider changing that to a normal for loop for the Array:

    for (var i = 0, l = data.messages.length; i < l; i++) {
        var obj = data.messages[i];
        // ...
    }
    

提交回复
热议问题