Skip to content

Loop through object JavaScript

  • by

To loop through an object in JavaScript, you can use methods like for...in loop, Object.keys(), or Object.entries(). These methods allow you to iterate over the properties of an object and perform actions based on each property.

Here’s the basic syntax for looping through an object in JavaScript using a for...in loop:

const obj = { key1: value1, key2: value2, key3: value3 };

for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    // Perform actions with obj[key]
  }
}

Alternatively, you can use Object.keys() to get an array of the object’s keys and then iterate over them using a loop:

const obj = { key1: value1, key2: value2, key3: value3 };

Object.keys(obj).forEach(function(key) {
  // Perform actions with obj[key]
});

Lastly, you can use Object.entries() to get an array of key-value pairs and iterate over them:

const obj = { key1: value1, key2: value2, key3: value3 };

Object.entries(obj).forEach(function([key, value]) {
  // Perform actions with key and value
});

Loop through object JavaScript examples

Simple example code to iterate over an object:

for…in loop: The for...in loop iterates over all enumerable properties of an object, including inherited ones.

const obj = { a: 1, b: 2, c: 3 };

for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(key + ': ' + obj[key]);
  }
}

Object.keys(): The Object.keys() method returns an array of an object’s own enumerable property names. You can then iterate over this array using a loop.

const obj = { a: 1, b: 2, c: 3 };

Object.keys(obj).forEach((key) => {
  console.log(key + ': ' + obj[key]);
});

Object.entries(): The Object.entries() method returns an array of an object’s own enumerable property key-value pairs, represented as arrays. You can use this method to iterate over both the keys and values.

const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj).forEach(([key, value]) => {
  console.log(key + ': ' + value);
});

Output:

Loop through object JavaScript

Do comment if you have any doubts or suggestions on this Js Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading