Author -  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 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY