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 :)
4 Answers 4
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);
}
Comments
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.
1 Comment
Sadly, "modern" does not include IE 8 ftwThis 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);
}
Comments
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]
}
for...indocumentation.