I am trying to loop through the following json array:
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": ""
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": ""
}
And have tried the following
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}
But for some reason I'm only getting the first part, id 1 values.
Any ideas?
14 Answers
Your JSON should look like this:
let json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": ""
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": ""
}];
You can loop over the Array like this:
for(let i = 0; i < json.length; i++) {
let obj = json[i];
console.log(obj.id);
}
Or like this (suggested from Eric) be careful with IE support
json.forEach(function(obj) { console.log(obj.id); });
There's a few problems in your code, first your json must look like :
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": ""
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": ""
}];
Next, you can iterate like this :
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(json[key].id);
alert(json[key].msg);
}
}
And it gives perfect result.
See the fiddle here :
try this
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": ""
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": ""
}];
json.forEach((item) => {
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
var arr = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": ""
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": ""
}
];
forEach method for easy implementation.
arr.forEach(function(item){
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
Since i already started looking into it:
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": ""
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": ""
}]
And this function
var iterateData =function(data){ for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}};
You can call it like this
iterateData(data); // write 1 and 2 to the console
Update after Erics comment
As eric pointed out a for in loop for an array can have unexpected results. The referenced question has a lengthy discussion about pros and cons.