How to Modify Object Properties in an Array Using forEach?
Nov 13, 2024 am 12:35 AMTraversing 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development
