Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Through Array inside Object in Javascript [duplicate]

Possible Duplicate:
Loop through Json object

{
  "data": [
    {
      "name": "Jen",
      "id": "1"
    },
    {
      "name": "Steve",
      "id": "8"
    }
  ]
}

A server I'm interacting with responds with the above.

I'm trying to loop through itenter code here for the For..in statement.

This is what I'm trying to do:

for (var item in response.data) {
  console.log(item.name);
}

This doesn't work. What went wrong?

Thank you

I GOT IT to work with the following after reading the comment:

for (var item in response.data) {
  console.log(response.data[item].name);
}

I was able to get a list of names...

Can someone dissect the response as to why it worked?

like image 377
William Sham Avatar asked Feb 24 '12 01:02

William Sham


People also ask

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.

Can you loop through an object JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

How do you iterate through an array of objects in react?

To loop through an array of objects in React:Use the map() method to iterate over the array. The function you pass to map() gets called for each element in the array. The method returns a new array with the results of the passed in function.


2 Answers

data is actually an array (denoted by []), rather than an object so you want a regular for loop rather than a for in.

for (var i = 0; i<response.data.length; i++) {
  // use i as an array index
  console.log(response.data[i].name);
}

In JavaScript, the for in construct is used for iterating over object properties, but to iterate an array an incremental for loop is typically used.

like image 163
Michael Berkowski Avatar answered Oct 22 '22 15:10

Michael Berkowski


Check out: Why is using "for...in" with array iteration a bad idea?

For...in iterates through names of the properties of an object. Array items are also considered "properties", so for..in iterates through indexes (which are 0, 1 in your case). As expected when you use response.data[0] you get first element of your array.

like image 41
Alexei Levenkov Avatar answered Oct 22 '22 16:10

Alexei Levenkov