Iterate through object JavaScript | Example code

  • by

Use for in loop to Iterate through objects in JavaScript. Other options map(), forEach(), or a for..of loop will not work

for (const item in items) {
  console.log(item)
}

You can also call Object.entries() to generate an array with all its enumerable properties, and loop through that, using any of the above methods:

Iterate through object JavaScript

Simple example code where for...in statement iterates over all enumerable properties of an object.

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

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

Output:

Iterate through object JavaScript

Another example code

const users = [
    { id: 0, name: 'John' },
    { id: 1, name: 'Wayne' },
    { id: 2, name: 'David' },
    ];

    for (const user in users) {
      console.log(user)
    }

Using Object entries()

This method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.

const object1 = {
  a: 'somestring',
  b: 42
};

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

Output:

> "a: somestring"
> "b: 42"

For most objects, use for .. in :

for (let key in yourobject) {
  console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
    console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (let key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}

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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.