How to iterate over objects using array methods

stu

Stu Finn

Posted on February 22, 2019

How to iterate over objects using array methods

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 more) that allow us to easily iterate over an array. Sweet!

const sampleArray = [I, love, technology];

sampleArray.forEach( (word) => {
    console.log(word);
});

// I
// love
// technology
Enter fullscreen mode Exit fullscreen mode

Objects are super too, in my humble opinion. With key/value pairs we only need a key name and we can get the associated value.

const sampleObject = {
    word1: "Always",
    word2: "and",
    word3: "forever"
};

// We can use either dot- or bracket-notation to access values:

console.log(sampleObject.word1);    // Always

console.log(sampleObject['word3']);    // Forever
Enter fullscreen mode Exit fullscreen mode

Boom!

What seems less awesome, though, is that array methods like .forEach(), .map(), etc… don’t work on objects. Noooooo!

[Insert sad-face here]

But don’t despair! There is a way to use array methods to easily iterate over objects, using the Object.keys() method. Let me explain:

What's Object.keys( ), you say?

Object.keys() is a built in Javascript method that takes any object as a parameter, and returns an array of that object’s keys.

For example:

console.log(Object.keys(sampleObject));

//  [“word1”, “word2”, “word3”] 
Enter fullscreen mode Exit fullscreen mode

Right on!

So as a workaround, we can use the returned array of keys to iterate over our object using an array method such as .forEach(). Sick!

Let me show you:

// here we now have an array of sampleObject’s keys
const arrayOfKeys = Object.keys(sampleObject);  

// we can use the key to call up each piece of Object data 
arrayOfKeys.forEach( key => console.log( sampleObject[key] ); 

// Always
// and
// forever
Enter fullscreen mode Exit fullscreen mode

WHAAAAAT?! Beautiful! *wipes away a single tear*

Now you know how to easily iterate over an Object using at least one array method. Please use your new powers responsibly!

I love technology

  • For more information on array methods see the MDN webdocs.

  • To learn about some of the best array methods out there, check out this handy article.

Many thanks to Wes Bos for pointing this out in his React for Beginners course. It's a really great course.

💖 💪 🙅 🚩
stu
Stu Finn

Posted on February 22, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related