How to Use Foreach Object in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Create PDF File in Node JS?
- How to Create Basic API in Node JS Express?
- How to find Files by Extension in Node JS?
- How to Move File in Folder using Node JS?
- How to Get File Size in Node JS?
- How to Check File is Exist or Not in Node JS?
- How to Create Directory if does not Exists in Node JS?
- How to Delete File If Exists in Node JS?
- How to Send Email using Gmail Account in Node.js?
- How to Get Current Date and Time in Node JS?
- How to Get Query String Value in Node.js?
- Node JS Express Route with Parameters Example
- How to Create Route in Node JS Express JS?