1

I have a javascript array written like this...

var json = [
    {"id":"1", "title":"Test 1", "comment":"This is the first test"},
    {"id":"2", "title":"Test 2", "comment":"This is the second test"}
];

what I am trying to do is get each one of the ids.

I have been trying this

for(x in json[0]){
    alert(x.id);        
}

But no luck, can someone point me in the right direction? Please and thank you :)

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user979331
  • 11,039
  • 73
  • 223
  • 418
  • possible duplicate of [for ... in loop with string array outputs indices](http://stackoverflow.com/questions/7480020/for-in-loop-with-string-array-outputs-indices) – Felix Kling Feb 17 '12 at 18:21
  • You probably find it helpful as well to read the [`for...in` documentation](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in). – Felix Kling Feb 17 '12 at 18:22

4 Answers4

5

x in your example is giving you the indexes of you array, not the objects. You could do:

for(x in json) {
    alert(json[x].id);        
}

but to loop through an array you're really better off with a "regular" for loop

for (var i = 0, max = json.length; i < max; i++) {
    alert(json[i].id);
}
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
4

Any modern browser will allow you to do it easily:

var ids = json.map(function(i) { return i.id; });
// and now you have an array of ids!

Sadly, "modern" does not include IE 8 and earlier.

You can also do the "mundane" form, which is guaranteed to work in all browsers. I see Adam Rackis has beat me to it though, so I 'll go upvote his answer and you should probably do so as well.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • +1 - nice - I really need to start using these ES5 methods more. And `Sadly, "modern" does not include IE 8` ftw – Adam Rackis Feb 17 '12 at 18:27
1

This is one possible solution:

var json = [{"id":"1","title":"Test 1","comment":"This is the first test"},{"id":"2","title":"Test 2","comment":"This is the second test"}];

for (var i = 0, len = json.length; i < len; i++) {
    alert(json[i].id);
}
simshaun
  • 21,263
  • 1
  • 57
  • 73
1

A for(x in y) loop in JavaScript gives you the indexes in that array (e.g., so that x[y] gives you the current element).

The two proper ways to loop through an array in JavaScript are:

for(x = 0; x < y.length; x++) { // (this can only loop through arrays)
  // do something with y[x]
}
for(x in y) { // (this can loop through objects too)
  // do something with y[x]
}
Frxstrem
  • 38,761
  • 9
  • 79
  • 119