Home > Web Front-end > JS Tutorial > How to Modify Object Properties in an Array Using forEach?

How to Modify Object Properties in an Array Using forEach?

Susan Sarandon
Release: 2024-11-13 00:35:02
Original
963 people have browsed it

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);
});
Copy after login

To use bracket notation, enclose the property name in brackets:

myArray.forEach(function (object) {
    console.log(object["x"]);
});
Copy after login

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);
});
Copy after login

Output:

{ x: 3, y: 2 }
{ x: 5, y: 4 }
{ x: 7, y: 6 }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template