Loop or Iterate through Array of Objects in JavaScript

In this tutorial, we are going to learn different ways to loop or iterate through an array of objects in JavaScript.

First way: ForEach method

Let's use es6 provided forEach() method which helps us to iterate over the array of objects:
function demo(){
   let users = [
       {
           firstName: "Ramesh",
           lastName: "Fadatare",
           emailId : "[email protected]"
       },
       {
            firstName: "Tony",
            lastName: "Stark",
            emailId : "[email protected]"
        },
        {
            firstName: "Tom",
            lastName: "Cruise",
            emailId : "[email protected]"
        }
   ]

   users.forEach((user)=> {
        console.log(user.firstName)
        console.log(user.lastName)
        console.log(user.emailId)
   });    
}

demo();
Output:
Ramesh
Fadatare
[email protected]
Tony
Stark
[email protected]
Tom
Cruise
[email protected]
The forEach method takes the callback function as an argument and runs on each object present in the array.
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
Refer below screenshot:

Second way: For of loop

Let's use for of loop to iterate over the array of objects in JavaScript:
function demo1(){
    let users = [
        {
            firstName: "Ramesh",
            lastName: "Fadatare",
            emailId : "[email protected]"
        },
        {
             firstName: "Tony",
             lastName: "Stark",
             emailId : "[email protected]"
         },
         {
             firstName: "Tom",
             lastName: "Cruise",
             emailId : "[email protected]"
         }
    ]
 
    for(let user of users){
        console.log(user.firstName)
         console.log(user.lastName)
         console.log(user.emailId)
    }   
 }

demo1();
Output:
Ramesh
Fadatare
[email protected]
Tony
Stark
[email protected]
Tom
Cruise
[email protected]

Related JavaScript Examples


Comments