How to Loop Through or Enumerate a JavaScript Object

From time to time, there may be a need to loop through objects in JavaScript. It is mainly done with the for..in loop.

However, looping through all key-value pairs for an object, you are looping through them as well. The for..in loop iterates through properties in the Prototype chain. To solve this problem, you should check if the property belongs to the object or not. It is done with hasOwnProperty .

for (let prop in object) {
  if (object.hasOwnProperty(prop)) {
    // Do thing here
  }
}

There is another method which demands, first, to turn objects into arrays and loop through arrays. Thus, there are additional methods looping through the array.

Object.keys

Here's the example of looping through the array with the Object.keys:

Javascript object keys
const personSalary = { engineer: 1500, programmer: 2500, lawyer: 2000, } const keys = Object.keys(personSalary) console.log(keys) // [engineer, programmer, lawyer]

The important point here is the use of for...of instead of for..in. Otherwise, it will return undefined on named properties, and Object.keys() ensures the use of only the object's properties without the whole prototype-chain properties.

Object.entries

The Object.entries() returns an array of enumerable string-keyed property [key, value] pairs of a given object, in the same order as for..of loop provides with one difference that for...of enumerates properties in the prototype chain. Using Object.entries, you can cut the array into the key and property:

for (let [key, value] of Object.entries(p)) {
  console.log(`${key}: ${value}`);
}
Example:
Javascript object enteries
const personSalary = { engineer: 1500, programmer: 2500, lawyer: 2000, } for (let [key, value] of Object.entries(personSalary)) { console.log(`${key}: ${value}`); }

The for...in and for...of Loops

The for...in loop iterates a specified variable over the properties of an object. It iterates over "enumerable" properties of the object and applies to all objects that have these properties.

An enumerable property is a property of an object with true Enumerable value. By calling property.enumerable, you can see whether a property is enumerable. It will return true or false.

The for...of statement is used to create a loop that allows iterating over arrays or other iterable objects, such as Arrays, Strings, Maps and Sets, etc. very easily. This method is used for iterating over "iterable collections" that are objects that have a [Symbol.iterator]property.