I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
Here's an example on how you can do it :)
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
Also in $.each you can use arrow function like below
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
If you want to access a specific property on each object: