How to loop through object in JavaScript(es6)

How to loop through object in JavaScript(es6)

In this tutorial, we are going to learn different ways to loop through an object in JavaScript.

For in loop

for in loop helps us to get the object key on each iteration by using that we can access the object value.

const obj = {
   id:1,
   name: "gowtham",
   active: true
}

for (let key in obj){
   if(obj.hasOwnProperty(key)){
     console.log(`${key} : ${obj[key]}`)
   }
}

//first iteration key is id
//second iteration key is name
//third iteration key is active

Note: we used obj.hasOwnProperty(key) method, to make sure that property belongs to that object because for in loop also iterates over an object prototype chain.

Object.keys

The Object.keys() method takes the object as an argument and returns the array with given object keys.

By chaining the Object.keys method with forEach method we can access the key, value pairs of the object.

Example:

const obj = {
   id:1,
   name: "gowtham",
   active: true
}

Object.keys(obj).forEach(key=>{
   console.log(`${key} : ${obj[key]}`);
});

Object.values

The Object.values() method takes the object as an argument and returns the array with given object values.

By using this method we can only access the object values.

Example:

Object.values(obj).forEach(value=>{
   console.log(value);
});

Object.entries

The Object.entries() method returns the array with arrays which are [key,value] pairs of the given object.

Example:

Object.entries(obj).forEach(([key,value])=>{
    console.log(`${key}:${value}`)
})

Object.getOwnPropertyNames

The Object.getOwnPropertyNames method also returns the array with given object properties or keys(including non-enumberable properties).

Example:

Object.getOwnPropertyNames(obj).forEach(key=>{
    console.log(`${key}:${obj[key]}`);
})