How to use forEach with an Array of Objects in JavaScript ?

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:

ParameterDescription
Callback functionA function called for each element of the array, performing operations on the current element.
Current ValueHolds 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: "w3wiki", 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(", ")}`);
    }
});

Output
w3wiki 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}`);
});

Output
The 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.



Contact Us