by Sai gowtham

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]}`);
})

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course