loading...
Cover image for Iterating over object properties in JavaScript

Iterating over object properties in JavaScript

coder4_life profile image coder4life ・1 min read

There are a few ways to iterate over object properties in JavaScript but key to all of them is Object.entries() which returns an array of a given object as key-value.

const myObject = {
  name: 'John Doe',
  age: 44,
  city: 'Paris',
  country: 'France',
};

const myObjectAsArray = Object.entries(myObject);

// Option 1:
myObjectAsArray.map(item => {
  console.log(item);
})

// Option 2:
myObjectAsArray.forEach(item => {
  console.log(item);
})

// Option 3:
for (let [key, value] of myObjectAsArray) {
  console.log(`${key}: ${value}`);
}

As video:

Let me know in the comments how you would do it. Are there better ways of doing this?

Discussion

pic
Editor guide