Using Object.keys() to Turn Javascript Objects into Array

Laina Karosic
3 min readNov 25, 2019

--

You’re fetching APIs, and you finally get the data back that you want! Yay!

When you fetch and that response comes back right away!

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:

An object is a collection of key-value pairs.

The object ‘thanksgiving’ has a cornucopia of keys and values. In the console, the object will look something like this:

The curly brackets are a giveaway that you’re dealing with an object, but not specifically an array.

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).

Using Object.keys() on the object thanksgiving

If we console.log() this value, we will see it returns:

The array we’ve been waiting for! Hip-hip — array!

So now let’s try .forEach() on this new array of menu categories:

And…

Voila! Here we have a nice return of the keys of our newly created array.

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?!?

Don’t worry Joey, there’s a method to get that turkey.

There’s a method for that:

Object.values() — what do you think this will return?

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?

--

--