ItSolutionStuff.com

How to Use Foreach Object in Node.js?

By Hardik Savani • March 25, 2023
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: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Create PDF File in Node JS?

Read Now →

How to Create Basic API in Node JS Express?

Read Now →

How to find Files by Extension in Node JS?

Read Now →

How to Move File in Folder using Node JS?

Read Now →

How to Get File Size in Node JS?

Read Now →

How to Check File is Exist or Not in Node JS?

Read Now →

How to Create Directory if does not Exists in Node JS?

Read Now →

How to Delete File If Exists in Node JS?

Read Now →

How to Send Email using Gmail Account in Node.js?

Read Now →

How to Get Current Date and Time in Node JS?

Read Now →

How to Get Query String Value in Node.js?

Read Now →

Node JS Express Route with Parameters Example

Read Now →

How to Create Route in Node JS Express JS?

Read Now →