gafasmill gafasmill - 4 months ago 10
JSON Question

Javascript JSON Loop not counting more than 1 entry

I am reading some json code and at the end added a log that would give me the id.
My problem is that although there are 2 entries the log is only counting 1 and stops there.

var json = [{"main":[{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}]}];

for(var i = 0; i < json.length; i++) {
var obj = json[i];

console.log(obj['main'][i].id);
}


Why is it only counting the 1 and not the 2 ?

Answer

A few of the answers here are going to confuse the hell out of you! They're missing the fact that you have an array within an object within an array.

  • json is an array, with 1 element
  • that object has a property main which itself is an array
  • it is this "3rd level" array which you are trying to loop through

var json = [{"main":[{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "hello1@email.se"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
}]}];

for(var i = 0; i < json[0].main.length; i++) {
    var obj = json[0].main[i];

    console.log(obj.id);
}