202

I am trying to loop through the following json array:

{
  "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"
}

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?

Syscall
  • 19,327
  • 10
  • 37
  • 52
Alosyius
  • 8,771
  • 26
  • 76
  • 120

14 Answers14

300

Your JSON should look like this:

let json = [{
    "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"
}];

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); });
Daniel L. VanDenBosch
  • 2,350
  • 4
  • 35
  • 60
Niklas
  • 23,674
  • 33
  • 131
  • 170
  • 16
    Or more concisely, `json.forEach(function(obj) { console.log(obj.id); });` – Eric Aug 14 '13 at 17:26
  • 6
    Unless on IE8 (as usual, everyone but IE ;) ) – lpiepiora Aug 14 '13 at 17:29
  • 8
    I think that example can be confuse, because var json is not a JSON object, but an array. In this case, .forEach works well, but when you use a json object, it doesn't work. – mold May 04 '18 at 15:30
39

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": "hello1@email.se"
},
{
"id" : "2", 
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];

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/

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
36

try this

var json = [{
    "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"
}];

json.forEach((item) => {
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});
chirag sorathiya
  • 1,223
  • 8
  • 29
18
var arr = [
  {
  "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"
  }
];

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);
});
Sivanesh S
  • 1,117
  • 10
  • 16
12

Since i already started looking into it:

var data = [{
    "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"
}]

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

Community
  • 1
  • 1
surfmuggle
  • 5,527
  • 7
  • 48
  • 77
  • 2
    **-1** - `for ... in ` loops should not be used for arrays – Eric Aug 14 '13 at 18:09
  • Array comprehensions use `for each`. `for ... in ...` is a language construct for enumerating object keys in an arbitrary order. That is not the right construct for an array. – Eric Aug 14 '13 at 20:18
10

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": "hello1@email.se" 
    }, 
    { 
        "id": "2", 
        "msg": "there", 
        "tid": "2013-05-05 23:45", 
        "fromWho": "hello2@email.se"
    }
]

And the loop is:

for (var key in data) {
   if (data.hasOwnProperty(key)) {
         alert(data[key].id);
   }
} 
Neuron
  • 5,141
  • 5
  • 38
  • 59
Shyam Shinde
  • 287
  • 1
  • 5
  • 14
8

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": "hello1@email.se"
  }, {
    "id": "2",
    "msg": "there",
    "tid": "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
  }]
}

Your JavaScript is simply

var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
  var curitem = json.item[x];
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Robb Penoyer
  • 81
  • 1
  • 1
7

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": "hello1@email.se"
}, {
    "id": "2",
        "msg": "there",
        "tid": "2013-05-05 23:45",
        "fromWho": "hello2@email.se"
}];

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/

lpiepiora
  • 13,659
  • 1
  • 35
  • 47
6

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]);
            }
       }
}
Kami Yang
  • 427
  • 5
  • 15
5

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.

Katana314
  • 8,429
  • 2
  • 28
  • 36
5

the very easy way!

var tire_price_data = JSON.parse('[{"qty":"250.0000","price":"0.390000"},{"qty":"500.0000","price":"0.340000"},{"qty":"1000.0000","price":"0.290000"}]'); 
tire_price_data.forEach(function(obj){
    console.log(obj);
    console.log(obj.qty);
    console.log(obj.price);
})

Thank you.

3
var json = {
    "persons": [
        {"name": "Lili", "age": 23, "is_student": true},
        {"name": "James", "age": 24, "is_student": true},
        {"name": "John", "age": 25, "is_student": false}
    ]
};

for (var key in json.persons) {
    for (var keyName in json.persons[key]) {
        alert(keyName + ': ' + (json.persons[key])[keyName]);
    }
}

//Output: name:Lili, age:23, is_student:true, ...

Lime莉茉
  • 101
  • 1
  • 3
2

A short solution using map and an arrow function

var data = [{
  "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"
}];
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));

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

var data = [{
  "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"
}, {
  "msg": "abcde",
  "tid": "2013-06-06 23:46",
  "fromWho": "hello3@email.se"
}];

data.filter(item=>item.hasOwnProperty('id'))
                .map((item, i) => console.log('Index:', i, 'Id:', item.id));
user2314737
  • 27,088
  • 20
  • 102
  • 114
0

you can use a for-loop then to get the values you can De-structure them

const arr = [
        {
            id:123,
            desc:"do something",
            isDone:false
        },
        {
            id:124,
            desc:"do something",
            isDone:true
        }
    ]

for(let _i in arr){
    let {id, desc, isDone} = arr[_i]
    // do something
    console.log({id, desc, isDone});
}


z9fr
  • 384
  • 5
  • 10