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!
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
myArray[j.x]
is logically incorrect.Use
(myArray[j].x);
insteadIn ECMAScript 2015 aka ES6, you can use a for..of loop to loop over an array of objects.
At the time of posting this answer, support is pretty non-existent for Internet Explorer, but through the use of a transpiler like Traceur or Babel, you can use new Javascript features like this without really having to worry about what browsers support what.
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
3. Transform to a new array
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
5. Create a new array based on the original but without modifying it
6. Count the number of each category
7. Retrieve a subset of an array based on particular criteria
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
9. Find an element in an array
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
Array object iteration, using jQuery, (use the second parameter to print the string).
Use forEach its a built-in array function.
Array.forEach()
: