DEV Community

How to iterate over objects using array methods

Stu Finn on February 22, 2019

Arrays are so freaking handy! They are a great way to store data and they have some really amazing “array methods” like .forEach() and .map() (and...
Collapse
 
wintercounter profile image
Victor Vincent

How about:

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value)
}

So much cleaner! People usually just scratching the surface of what JS can actually do.

Collapse
 
robaxelsen profile image
Robert Axelsen • Edited

Beautiful! This one is also nice:

Object.entries(obj).forEach(([key, value]) => {
  console.log(key, value);
});
Collapse
 
schester44 profile image
Steve Chester

Object.keys holds a special place in my heart. You can also use Object.entries as well.

Collapse
 
msinkgraven profile image
Matthew Sinkgraven

Don't forget Object.values ;)

Collapse
 
kenotron profile image
Kenneth Chau

sampleObject[word3] should be sampleObject['word3'], eh?

Collapse
 
stu profile image
Stu Finn

You're right! Ah, thanks for catching that - fixed now. Cheers

Collapse
 
the_riz profile image
Rich Winter

"New", but...
Onject.values
Object.entries

and while you have to know some about the enumerable properties of the object and its prototype-
for(let i in obj){ ... }

Collapse
 
wintercounter profile image
Victor Vincent

That's why there is for-of