Loop or Iterate over an Object in JavaScript


In this post, I show you three different ways to loop or iterate over an Object in JavaScript.

3 Ways to Loop an Object in JavaScript

1. Using Object.keys() Method

var user = {
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: 'ramesh@gmail.com',
    age: 29
}

const keys = Object.keys(user)
console.log(keys) // [apple, orange, pear]
for (const key of keys) {
    console.log(" key :: " + key);
    console.log(" value :: " + user[key]);
}
Output:
key :: firstName
value :: Ramesh
key :: lastName
value :: Fadatare
key :: emailId
value :: ramesh@gmail.com
key :: age
value :: 29

2. Using Object.entries() Method

var user = {
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: 'ramesh@gmail.com',
    age: 29
}

const entries = Object.entries(user)

for (const [key, value] of entries) {
    console.log(`Key Value Pair -> ${key} ${value}`)
}
Output:
Key Value Pair -> firstName Ramesh
Key Value Pair -> lastName Fadatare
Key Value Pair -> emailId ramesh@gmail.com
Key Value Pair -> age 29

3. Using Object.hasOwnProperty() Method

var user = {
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: 'ramesh@gmail.com',
    age: 29
}

for (var key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " -> " + user[key]);
    }
}
Output:
firstName -> Ramesh
lastName -> Fadatare
emailId -> ramesh@gmail.com
age -> 29

Reference

Comments