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 : "ramesh@gmail.com"
},
{
firstName: "Tony",
lastName: "Stark",
emailId : "tony@gmail.com"
},
{
firstName: "Tom",
lastName: "Cruise",
emailId : "tom@gmail.com"
}
]
users.forEach((user)=> {
console.log(user.firstName)
console.log(user.lastName)
console.log(user.emailId)
});
}
demo();
Output:
Ramesh
Fadatare
ramesh@gmail.com
Tony
Stark
tony@gmail.com
Tom
Cruise
tom@gmail.com
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 : "ramesh@gmail.com"
},
{
firstName: "Tony",
lastName: "Stark",
emailId : "tony@gmail.com"
},
{
firstName: "Tom",
lastName: "Cruise",
emailId : "tom@gmail.com"
}
]
for(let user of users){
console.log(user.firstName)
console.log(user.lastName)
console.log(user.emailId)
}
}
demo1();
Output:
Ramesh
Fadatare
ramesh@gmail.com
Tony
Stark
tony@gmail.com
Tom
Cruise
tom@gmail.com
Related JavaScript Examples
- How to Empty an Array in JavaScript //Popular
- JavaScript Utility Methods //Popular
- Best JavaScript Utility Libraries //Popular
- Check if Map is Null or Empty in Java //Popular
Comments
Post a Comment
Leave Comment