I am trying to loop through the following:
{
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
I want to retrieve msgFrom
and msgBody
I've tried:
for (var key in data) {
var obj = data[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
But the console log prints [Object]
Any ideas what im doing wrong?
Best Answer
It appears you may just have missed the
"messages"
property in thedata
, so the loop is likely iterating the rootObject
rather than theArray
:Unless
data
was set tomessages
before the given snippet.Though, you should consider changing that to a normal
for
loop for theArray
: