Skip to content
loading...

Iterating over object properties in JavaScript

twitter logo ・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?

twitter logo DISCUSS
Classic DEV Post from Jun 9 '19

Explain CI/CD like I'm five.

Explanation of CI/CD, discuss, developer

coder4life profile image
Join DEV

Learn how to be better at computers and programming and stuff. DEV 4 life.