How to Use Foreach Object in Node.js?

By Hardik Savani March 25, 2023 Category : Node JS

In Node.js, you can use the forEach() method to iterate over an array of objects and perform an operation on each object. Here's an example of how to use forEach() to iterate over an array of objects:

Example 1:

const myObjects = [

{ name: "Hardik", age: 30 },

{ name: "Paresh", age: 25 },

{ name: "Mahesh", age: 40 },

];

myObjects.forEach((object) => {

console.log(object.name + " is " + object.age + " years old");

});

In the above example, the forEach() method is used to iterate over the myObjects array. The object parameter represents each object in the array. The arrow function then performs an operation on each object, which is to log the name and age of each person to the console.

Example 2:

You can also use the forEach() method to modify the objects in the array. For example:

myObjects.forEach((object) => {

object.age += 1;

});

console.log(myObjects);

In this example, the forEach() method is used to iterate over the myObjects array and add 1 to the age property of each object. The modified objects are then logged to the console.

Note that the forEach() method does not return a new array - it simply iterates over the existing array and performs an operation on each object. If you need to create a new array based on the objects in the original array, you can use methods like map().

I hope it can help you...

Tags :
Shares