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 :)

2

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

+1 - nice - I really need to start using these ES5 methods more. And Sadly, "modern" does not include IE 8 ftw
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);
}

Comments

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]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.