0
var myJSON =     
{"data":
    [{"obj1":"value1",
      "obj2":"value2"},

     {"obj1":"value3",
      "obj2":"value4"},

     {"obj1":"value5",
     "obj2":"value6"}]
};

I've got an array looking like one above. I'd like to loop through each obj2 and get the values. How can this be done in Javascript/jQuery?

I tried using:

for (var i = 0; i < myJSON.data.length; i++) {
    console.log(i.obj2);
}

but it looks as though myJSON.data doesn't return a length...

3 Answers 3

2

i is only an iterator you can use to access the array

for (var i = 0; i < myJSON.data.length; i++) {
    console.log(myJSON.data[i].obj2);
}
Sign up to request clarification or add additional context in comments.

Comments

1
for (var i = 0; i < myJSON.data.length; i++) {
    console.log(myJSON.data[i].obj2);
}

Comments

0

The problem is that you're trying to access the obj2 key from your i variable, which isn't your array. Try this way:

for (var i = 0; i < myJSON.data.length; i++) {
    console.log(myJSON.data[i].obj2);
}

Other ways to do the same:

for(var i in d=myJSON.data){
  console.log(d[i].obj2);
}

or

myJSON.data.forEach(function(a){
  console.log(a.obj2)
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.