Home >Web Front-end >JS Tutorial >How to Modify Object Properties in an Array Using forEach?
Traversing Arrays of Objects and Manipulating Their Properties
To iterate through an array containing objects and manipulate their properties, one approach is to utilize the forEach method. This built-in array function allows you to specify a function to be executed for each element of the array.
Accessing Object Properties within the Loop
To access an object's property within the forEach loop, you can use dot notation or bracket notation. For example, to access the x property of an object using dot notation:
myArray.forEach(function (object) { console.log(object.x); });
To use bracket notation, enclose the property name in brackets:
myArray.forEach(function (object) { console.log(object["x"]); });
Example: Modifying Object Properties
The following code demonstrates how to modify object properties within a forEach loop:
const myArray = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 } ]; myArray.forEach(function (object) { object.x += 2; // Increment the x property of each object console.log(object); });
Output:
{ x: 3, y: 2 } { x: 5, y: 4 } { x: 7, y: 6 }
The above is the detailed content of How to Modify Object Properties in an Array Using forEach?. For more information, please follow other related articles on the PHP Chinese website!