How to loop through object in JavaScript(es6)

This tutorial will show you how to loop through JavaScript objects.

For in loop

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

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 accepts the object as an argument, and returns an array with the given object keys.

We can access keys. and value pairs by chaining the Object.keys()  methods with the forEach  method.

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 accepts an  object as an argument, and returns an array with the given object values.

This method allows us to only access object values.

Example:

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

Object.entries

The  Object.entries()  method returns an  arrays with arrays that are [key,value]  pairs for 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-enumerable properties).

Example:

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

 

Exit mobile version