How to use forEach with an Array of Objects in JavaScript ?
Last Updated :
10 Jun, 2024
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills.
Syntax:
array.forEach( function( currentValue, index, array);
Parameters:
Parameter | Description |
---|
Callback function | A function called for each element of the array, performing operations on the current element. |
Current Value | Holds the value currently being processed within the array. |
Index | (Optional) Holds the index of the current value, starting from 0. |
array | (Optional) The complete array on which the method is called. |
Importance of Using forEach()
:
Employing forEach()
with an array of objects is important for:
- Iterating over arrays to access each object.
- Performing operations like logging, updating, or transforming object properties.
- Simplifying code for better readability and maintainability.
Example 1: Iterating over the array of objects using forEach.
JavaScript
let arrayOfObject = [
{ name: "GeeksforGeeks", location: "Noida" },
{
courses: [
"DSA",
"DevOps Bootcamp",
"GATE preparation course etc...."
]
},
];
arrayOfObject.forEach((obj) => {
if (obj.name) {
console.log(`${obj.name} is
located in ${obj.location}`);
} else if (obj.courses) {
console.log(`Courses offered:
${obj.courses.join(", ")}`);
}
});
OutputGeeksforGeeks is
located in Noida
Courses offered:
DSA, DevOps Bootcamp, GATE preparation course etc....
Example 2: Using forEach to iterate over the array of Employee details.
JavaScript
const Employees = [
{
name: 'John', age: 35,
team: "Data Strcuture & Alogirthm"
},
{
name: 'Doe', age: 26,
team: "DevOps Bootcamp"
},
{
name: 'Ben', age: 21,
team: "Data Science"
}
];
// Using forEach loop.
Employees.forEach((Employees) => {
console.log(
`
${Employees.name}is ${Employees.age} years old
and is the part of ${Employees.team} team.\n
`
);
});
Output
Johnis 35 years old
and is the part of Data Strcuture & Alogirthm team.
Doeis 26 years old
and is the part of DevOps Bootcamp team.
Benis 21 years old
and is the part of Data Science team.
...
Example 3: Find the area of the rectangle using forEach by iterating over the dimensions array.
JavaScript
let dimensions = [
{
rectangle1: {
length: 10,
width: 5
}
},
{
rectangle2: {
length: 20,
width: 10
}
},
{
rectangle3: {
length: 30,
width: 15
}
}
];
dimensions.forEach(rectangleObj => {
const rectangle = Object.keys(rectangleObj)[0];
const { length, width } = rectangleObj[rectangle];
console.log(`The area of ${rectangle} is:
${length * width}`);
});
OutputThe area of rectangle1 is:
50
The area of rectangle2 is:
200
The area of rectangle3 is:
450
Common Use Cases
While detailed examples will be discussed in the approaches section, here’s a brief overview:
- Logging Object Properties: Use
forEach(
) to print out object properties. - Modifying Object Properties: Update specific properties of each object in the array.
Mastering the forEach()
method with arrays of objects enhances your ability to manipulate and process data efficiently. This guide introduces the importance and prerequisites, preparing you for detailed method explanations. By focusing on practical applications, you can improve your JavaScript proficiency and code effectiveness.
Similar Reads
How to use async/await with forEach loop in JavaScript ? Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to
2 min read
How to convert a map to array of objects in JavaScript? A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How To Iterate an Array using forEach Loop in JavaScript? Iterating through an array in JavaScript can be done in multiple ways. One of the most common methods is using the traditional for loop. The modern approach to iterate the array which is by using the forEach method. This method is different from the traditional approach as it uses a functional appro
1 min read
How to Access Array of Objects in JavaScript ? Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array.How
4 min read
How to get Values from Specific Objects an Array in JavaScript ? In JavaScript, an array is a data structure that can hold a collection of values, which can be of any data type, including numbers, strings, and objects. When an array contains objects, it is called an array of objects. Table of Content Using the forEach() methodUsing the map() methodUsing the filte
2 min read
How to Move a Key in an Array of Objects using JavaScript? The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.You can move or add a key to these types of arrays using the below methods in JavaScript:Table of ContentUsing Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce() met
5 min read