Javascript循环通过对象数组? [英] Javascript loop through object array?
本文介绍了Javascript循环通过对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试循环使用以下内容:
I am trying to loop through the following:
{
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
我想要检索 msgFrom
和 msgBody
我试过:
for (var key in data) {
var obj = data[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
但控制台日志打印 [对象]
任何想法我做错了什么?
Any ideas what im doing wrong?
推荐答案
看来你可能错过了数据$ c中的
messages
属性$ c>,所以循环可能会迭代根 Object
而不是数组
:
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];
// ...
}
这篇关于Javascript循环通过对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文