Javascript, Converting an Object to an Array of Objects.

Chris Burgin
Spark
Published in
2 min readDec 16, 2017

--

A while back I wrote an article that got some traction about converting an Array of Objects to an Object. Today we are going to do the opposite, convert an object to an array of objects.

You may be asking why, the answer is actually quite simple. In programing we are not always in control of the format in which our data is delivered to us. With this in mind it becomes important to understand how to convert our data into our desired format.

The Example

Using newer Javascript features there is an easy one liner that can achieve this result using Object.values().

const peopleObj = {
jim: {
name: "jim",
age: 20
},
tim: {
name: "tim",
age: 22
}
}
const peopleArray = Object.values(peopleObj)

In my opinion if you are using babel go ahead and use this, if not I will show below how you can do this with a more widely supported feature, Object.keys().

Note: The following example uses the peopleObj from the above example.

const peopleArray = Object.keys(peopleObj).map(i => peopleObj[i])

This second method is quite well supported. Check out both Object Values and Object Keys MDN documentation to learn where you may have issues with support and for more info on these features.

As a note, if you prefer a key valued pair check out Object Entries.

Thanks for reading! Please check out the below MDN documentation for more reading on this topic. Clap and follow for more articles!

Follow me on twitter @chrisburgin95 for occasional programming tweets. Thanks for reading!

--

--

Chris Burgin
Spark

Christ follower. Dog caretaker. Developer at Generation Tux.