Tuesday, 8 November 2016

Loop Through Array inside Object in Javascript











{
"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?


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...