[javascript] JavaScript loop through json array?

I am trying to loop through the following json array:

{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
}

And have tried the following

for (var key in data) {
   if (data.hasOwnProperty(key)) {
      console.log(data[key].id);
   }
}

But for some reason i am only getting the first part, id 1 values.

Any ideas?

This question is related to javascript json

The answer is


A bit late but i hope i may help others :D

your json needs to look like something Niklas already said. And then here you go:

for(var key in currentObject){
        if(currentObject.hasOwnProperty(key)) {
          console.info(key + ': ' + currentObject[key]);
        }
   }

if you have an Multidimensional array, this is your code:

for (var i = 0; i < multiDimensionalArray.length; i++) {
    var currentObject = multiDimensionalArray[i]
    for(var key in currentObject){
            if(currentObject.hasOwnProperty(key)) {
              console.info(key + ': ' + currentObject[key]);
            }
       }
}

var arr = [
  {
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
  }, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
  }
];

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);
});

your data snippet need to be expanded a little, and it has to be this way to be proper json. notice I just include the array name attribute "item"

{"item":[
{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
}]}

your java script is simply

var objCount = json.item.length;
for ( var x=0; x < objCount ; xx++ ) {
    var curitem = json.item[x];
}

Since i already started looking into it:

var data = [{
    "id": "1",
    "msg": "hi",
    "tid": "2013-05-05 23:35",
    "fromWho": "[email protected]"
}, {
    "id": "2",
    "msg": "there",
    "tid": "2013-05-05 23:45",
    "fromWho": "[email protected]"
}]

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.

Test with for(var i ...

But it seems that the follwing is quite save:

for(var i = 0; i < array.length; i += 1)

Although a test in chrome had the following result

var ar = [];
ar[0] = "a"; 
ar[1] = "b";
ar[4] = "c";

function forInArray(ar){ 
     for(var i = 0; i < ar.length; i += 1) 
        console.log(ar[i]);
}

// calling the function
// returns a,b, undefined, undefined, c, undefined
forInArray(ar); 

Test with .forEach()

At least in chrome 30 this works as expected

var logAr = function(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c

Links


A short solution using map and an arrow function

_x000D_
_x000D_
var data = [{_x000D_
  "id": "1",_x000D_
  "msg": "hi",_x000D_
  "tid": "2013-05-05 23:35",_x000D_
  "fromWho": "[email protected]"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "msg": "there",_x000D_
  "tid": "2013-05-05 23:45",_x000D_
  "fromWho": "[email protected]"_x000D_
}];_x000D_
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));
_x000D_
_x000D_
_x000D_

And to cover the cases when the property "id" is not present use filter:

_x000D_
_x000D_
var data = [{_x000D_
  "id": "1",_x000D_
  "msg": "hi",_x000D_
  "tid": "2013-05-05 23:35",_x000D_
  "fromWho": "[email protected]"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "msg": "there",_x000D_
  "tid": "2013-05-05 23:45",_x000D_
  "fromWho": "[email protected]"_x000D_
}, {_x000D_
  "msg": "abcde",_x000D_
  "tid": "2013-06-06 23:46",_x000D_
  "fromWho": "[email protected]"_x000D_
}];_x000D_
_x000D_
data.filter(item=>item.hasOwnProperty('id'))_x000D_
                .map((item, i) => console.log('Index:', i, 'Id:', item.id));
_x000D_
_x000D_
_x000D_


It is working. I just added square brackets to JSON data. The data is:

var data = [
    { 
        "id": "1",
        "msg": "hi", 
        "tid": "2013-05-05 23:35", 
        "fromWho": "[email protected]" 
    }, 
    { 
        "id": "2", 
        "msg": "there", 
        "tid": "2013-05-05 23:45", 
        "fromWho": "[email protected]"
    }
]

And the loop is:

for (var key in data) {
   if (data.hasOwnProperty(key)) {
         alert(data[key].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": "[email protected]"
},
{
"id" : "2", 
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];

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 : http://jsfiddle.net/zrSmp/


It must be an array if you want to iterate over it. You're very likely missing [ and ].

var x = [{
    "id": "1",
        "msg": "hi",
        "tid": "2013-05-05 23:35",
        "fromWho": "[email protected]"
}, {
    "id": "2",
        "msg": "there",
        "tid": "2013-05-05 23:45",
        "fromWho": "[email protected]"
}];

var $output = $('#output');
for(var i = 0; i < x.length; i++) {
    console.log(x[i].id);
}

Check out this jsfiddle: http://jsfiddle.net/lpiepiora/kN7yZ/


Well, all I can see there is that you have two JSON objects, seperated by a comma. If both of them were inside an array ([...]) it would make more sense.

And, if they ARE inside of an array, then you would just be using the standard "for var i = 0..." type of loop. As it is, I think it's going to try to retrieve the "id" property of the string "1", then "id" of "hi", and so on.


try this

var json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "[email protected]"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "[email protected]"
}];

json.forEach((item) => {
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});

Your JSON should look like this:

var json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "[email protected]"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "[email protected]"
}];

You can loop over the Array like this:

for(var i = 0; i < json.length; i++) {
    var 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); });