Home >Web Front-end >JS Tutorial >How to Loop and Access Properties in Arrays of Objects in JavaScript?
Looping and Accessing Properties in Arrays of Objects
In JavaScript, looping through an array containing objects requires a modified approach compared to simple value arrays.
Iterating Over the Objects
To iterate over the objects in an array, you can use the forEach() method. Unlike the basic loop structure, forEach() executes a callback function for each element in the array:
myArray.forEach((element) => { console.log(element); });
This code will log each object in the myArray array.
Accessing Object Properties
To access object properties within the loop, you can use dot notation or bracket notation:
forEach((element) => { console.log(element.x); // Dot notation console.log(element["y"]); // Bracket notation });
Example
Let's modify the code in your question to use forEach():
for (var j = 0; j < myArray.length; j++) { console.log(myArray[j].x); // This returns "undefined" } myArray.forEach((element) => { console.log(element.x); // This works });
In the first loop, it incorrectly tries to access the "x" property of the string "undefined." Using forEach() with an appropriate callback function allows you to successfully access and manipulate the properties of each object in the array.
The above is the detailed content of How to Loop and Access Properties in Arrays of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!