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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With