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?
Top comments (0)