How to apply loop on objects in JavaScript?

What are the ways to loop through objects in javascript?

When we talk about looping through objects, before ES6 we had only one option to loop through objects using for...in. But it has some drawback as it iterates through properties in the prototype chain and to check if property belongs to the object you can do this with hasOwnProperty. 

 

for (var property in object) {
  if (object.hasOwnProperty(property)) {
    // Rest code
  }
}

 

Better way to loop through objects: 

A better way is to convert object into an array and then loop through the array. There are three ways to convert object into an array:

1- Object.keys

2- Object.values

3- Object.entries

 

Object.keys

Object.keys returns an array that contains the properties of an object. 

const fruits = {
  apple: 38,
  orange: 27,
  pear: 64,
}

const keys = Object.keys(fruits)
console.log(keys) // [apple, orange, pear]

Object.values

Object.values creates an array that contains the values of every property in an object.

const fruits = {
  apple: 38,
  orange: 27,
  pear: 64,
}

const values = Object.values(fruits)
console.log(values) // [38, 27, 64]

Object.entries

Object.entries creates an array of arrays. Each inner array has two item. The first item is the property;

the second item is the value.

const fruits = {
  apple: 38,
  orange: 27,
  pear: 64,
}

const entries = Object.entries(fruits)
console.log(entries)
// [
//   [apple, 38],
//   [orange, 27],
//   [pear, 64]
// ]

It is good to use Object.entries because you get both the key and property values.
Looping through the array

Once you have converted the object into an array with Object.keys, Object.values, or Object.entries,

you can loop through it as if it was a normal array.

// Looping through arrays created from Object.keys
const keys = Object.keys(fruits)
for (const key of keys) {
  console.log(key)
}

// Results:
// apple
// orange
// pear

If you use Object.entries you might want to destructure the array into its key and property.

for (const [fruit, count] of entries) {
  console.log(`There are ${count} ${fruit}s`)
}

// Result
// There are 38 apples
// There are 27 oranges
// There are 64 pears