I have the following JSON:
{"data":[{"id":1,"client_id":1},{"id":2,"client_id":1}]}
I’m trying to do a for...in but something is not going well.
Look at my code:
for (post in data) {
console.log(post.client_id); //return undefined
}
But if I do this:
for (i=0 ; i<data.length; i++) {
console.log(data[i].client_id); //return the correct value
}
Why can’t I iterate with for..in in this case?
First off, you should NEVER iterate arrays with
for/in. That structure iterates properties of the object. You will get all the array elements, but you may also get other iterable properties of the object too.Arrays should always be iterated with a traditional
forloop as in:for (var i = 0; i < arr.length; i++).Second off, you have to make sure you’re following your own data structure properly. You have this:
which spread out some more looks like this:
So, your JSON is an object. That object has one property in it called
dataand that one property’s value is an array, which contains objects. You would get the first item in the array with this:Or the properties on that object with this:
You would iterate all the items in that array like this: