Skip to content

How to iterate over object properties in JavaScript?

Iterating over an object properties is such a common task in JavaScript. In this tutorial, we will learn different ways to iterate/loop JavaScript objects.

for..in

The for..in loop can be used to iterate over keys of an object and access the corresponding values.

const obj  = {name:"Anand", class:"X", score:89};

for(let key in obj){
    console.log(obj[key])
}

//Anand
//X
//89

Object.keys()

The Object.keys() method returns keys of an object with which you can iterate over and access the values.

const obj  = {name:"Anand", class:"X", score:89};

for(let key of Object.keys(obj)){
    console.log(obj[key])
}

//Anand
//X
//89

Object.values()

The Object.values() method returns values of an object with which you can iterate over and access each value.

const obj  = {name:"Anand", class:"X", score:89};

for(let value of Object.values(obj)){
    console.log(value);
}

//Anand
//X
//89

Object.entries()

Object.entries() method generates an array with all of object’s enumerable properties. You can use the cloned array to iterate over the key-values.

const obj  = {name:"Anand", class:"X", score:89};

Object.entries(obj).forEach(item => {
  console.log(item);
})

// ["name", "Anand"]
// ["class", "X"]
// ["score", 89]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.