Convert an object to array in JS
On simple objects, this is as easy as calling Object.keys or Object.entries
By: Ajdin Imsirovic 22 January 2021
Converting an object to an array is pretty easy in JavaScript. All we have to do is use Object.keys, or an even easier method to use, Object.entries.
Let’s say we have a simple object that we want to convert to an array:
There are a number of ways to do this:
- Using
Object.keys()
- Using
Object.entries()
Within the Object.keys()
approach, there are also a couple of ways of doing this.
In the first approach, we take the following three steps:
Here’s what each line above does:
- (1) we set up a
convertedArr
array to push items into - (2) we store the keys of our
tesla
object in a newkeysArr
array - (3) we run the
forEach()
method on thekeysArr
to push keys fromkeysArr
toconvertedArr
, and values fromtesla
toconvertedArr
A second approach doesn’t require a separate convertedArr
; instead, we use the fact that the map()
method, when run, returns a brand new array:
Here’s what’s each LOC’s doing:
- (1) we store the keys of our
tesla
object in thekeysArr
- (2) we run the
map()
methods onkeysArr
, mapping eachkey
into an array of two members: akey
as the first member, and atesla[key]
as the second member
With Object.entries()
, this process of coversion is made significantly more simple:
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.