Using Object.keys() to Turn Javascript Objects into Array
You’re fetching APIs, and you finally get the data back that you want! Yay!
But wait — what happens when the JSON response is in the form of an object and not the pretty array that you want to iterate through? There are several options, but I want to introduce you to a simpler, cleaner method called Object.keys().
Recap: Objects are collections of name-value pairs.Those values can be other collections of name-value pairs. Let’s look at this simple object:
The object ‘thanksgiving’ has a cornucopia of keys and values. In the console, the object will look something like this:
Objects are great but let’s say you want to be able to perform array-like methods on this object, such as iterating through each of these and sending each meal “key” to another function called, displayMenuCategories(). Unfortunately you can’t use .forEach() to iterate through an object, as that’s a special method for arrays only. So, to turn this object into an array of the keys, use Object.keys() and pass in the object (in this case the object is thanksgiving).
If we console.log() this value, we will see it returns:
So now let’s try .forEach() on this new array of menu categories:
And…
Object.keys() essentially extracts all the keys and returns a new array.
Now, what if you don’t want the meal categories, but rather the actual menu items (aka, the values not the keys)? What if you have NO CLUE what entree people eat for thanksgiving?!?
There’s a method for that:
And there we have it! Object.values() returns an array of all of the values.
Now I have one more for you to explore — what do you think Object.entries() will return?