W3docs

How to Loop Through or Enumerate a JavaScript Object

Read this tutorial and learn several useful methods of looping through or enumerate a JavaScript object. Try and copy the piece of the code right away.

From time to time, there may be a need to loop through objects in JavaScript. It is mainly done with the <kbd class="highlighted">for..in</kbd> loop.

However, looping through all key-value pairs for an object, you are looping through them as well. The <kbd class="highlighted">for..in</kbd> 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 <kbd class="highlighted">hasOwnProperty</kbd>.

javascript 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

javascript— editable

The important point here is the use of for...of instead of <kbd class="highlighted">for..in</kbd>. Since <kbd class="highlighted">Object.keys()</kbd> returns an array, for...of is the idiomatic choice for iterating over it. Additionally, <kbd class="highlighted">Object.keys()</kbd> ensures you only access the object's own properties, excluding those from the prototype chain.

Object.entries

The <kbd class="highlighted">Object.entries()</kbd> method returns an array of enumerable string-keyed property [key, value] pairs for a given object. It iterates over the object's own enumerable properties, avoiding the prototype chain traversal that <kbd class="highlighted">for..in</kbd> performs. Using <kbd class="highlighted">Object.entries</kbd>, you can destructure each array element into a key and a value:

javascript object entries

for (let [key, value] of Object.entries(p)) {
  console.log(`${key}: ${value}`);
}

Example:

Javascript object entries

javascript— editable

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

The <kbd class="highlighted">for...in</kbd> 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 <kbd class="highlighted">Enumerable</kbd> value. By calling <kbd class="highlighted">property.enumerable</kbd>, you can see whether a property is enumerable. It will return true or false.

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