JavaScript

How to loop through a plain JavaScript object

In this tutorial, we are going to see how to loop through a plain JavaScript object. Object is the basic building block of javascript and almost everything in it is an object. If we want to iterate through the objects in javascript, we can use for … in loop.
 

Using the for … in loop
let obj = {
   e1: 10,
   e2: 'Lorem Ipsum',
   e3: function () {
	console.log('Lorem Ipsum!');
   }
};

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

Output:

10
Lorem Ipsum
ƒ () {
	console.log('Lorem Ipsum!');
   }
 
The only problem with for … in loop is the order in which the key is not decided, it will also extract the keys from the property hierarchy. To avoid this we can use the hasOwnProperty() method.

for (var property in object) {
  if (object.hasOwnProperty(property)) {
    // Put your code here
  }
}

 

Better way to loop through an object

The best way to iterate over objects is to convert the object to an array first. Then you loop through the array.

You can convert an object to an array with the following methods:

  • Object.keys
  • Object.values
  • Object.entries

 

Object.keys

The Object.keys method creates an array containing the keys of an object.

const languages = {
  JavaScript: 50,
  Python: 45,
  Java: 30,
  PHP: 10,
}

const keys = Object.keys(languages)
console.log(keys)

Output:

["JavaScript", "Python", "Java", "PHP"]
 

Object.values

Object.values creates an array containing the values of each property of an object.

const languages = {
  JavaScript: 50,
  Python: 45,
  Java: 30,
  PHP: 10,
}

const values = Object.values(languages)
console.log(values)

Output:

[50, 45, 30, 10]

 

Object.entries

Object.entries creates an array of arrays. Each internal array has two elements. The first is the key and the second is the value.

const languages = {
  JavaScript: 50,
  Python: 45,
  Java: 30,
  PHP: 10,
}

const arr = Object.entries(languages)
console.log(arr)

Output:

[
    [JavaScript, 50],
    [Python, 45],
    [Java, 30],
    [PHP, 10]
 ]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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