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
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
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”]
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
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!
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.
Top comments (8)
How about:
So much cleaner! People usually just scratching the surface of what JS can actually do.
Beautiful! This one is also nice:
Object.keys holds a special place in my heart. You can also use Object.entries as well.
Don't forget Object.values ;)
sampleObject[word3] should be sampleObject['word3'], eh?
You're right! Ah, thanks for catching that - fixed now. Cheers
"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){ ... }
That's why there is
for-of