How to transform an object to an array of objects

Elliott
3 min readAug 1, 2020

An array of objects is a developer’s bread and butter.

You got an array, which means you can make use of all the great array methods like .map() , .filter() , .reduce() (and all the rest), making this data structure eminently loopable, and very easy to safely transform.

…And you got a bunch of individual objects that have predictable structure, and key/values that make it very easy to reference the exact data you want to work with.

The only thing that could make this perfect combination better, is perhaps a snappier name. An “arrObject” — as my friend once proposed 😆

Problem

What if you have an object and you want to convert that to an array of objects to do whatever you need to do?

Example data

const ingredients = {
cheese: 2,
lettuce: 3,
bacon: 1,
meat: 1,
};

Explanation

Honestly, there are a ton of different ways to do this, and if you check stack overflow, you will find no end to people giving advice about the problem.

However, this is the solution I like. It is cool, easy to read and very simple to understand.

The solution for this has two parts.

First, to get this Object into an array, we can use Object.keys object method, which will return an array of the keys in the ingredients object.

console.log(Object.keys(ingredients)) , this will return:

["cheese", "lettuce", "bacon", "meat"]

Second, we’ll use the .reduce() array method, in order to take this array and reconstruct our data.

Solution 1: The long way

let ingredients= {lettuce: 0, bacon: 0, cheese: 1, meat: 4};let output = Object.keys(ingredients).reduce((acc, curr) => {      

acc.push({
name: curr,
count: ingredients[curr],
})
return acc;
}, []);

If you console.log output , you’ll see we have successfully converted this to an array of objects:

Solution 2: Use concat to shorten this up

This will apply the same methodology as before, but we can tighten things up by using .concat() array method:

let ingredients= {lettuce: 0, bacon: 0, cheese: 1, meat: 4};let output = Object.keys(ingredients).reduce((acc, curr) => acc.concat([{ 
name: curr,
count: ingredients[curr],
}]), []);

Solution 3: Use the spread operator

Another short solution to keep the code clean and shorter:

let ingredients= {lettuce: 0, bacon: 0, cheese: 1, meat: 4};let o = Object.keys(ingredients).reduce((acc, curr) => [...acc, { 
name: curr,
count: ingredients[curr],
}], []);

This does the same thing as concat above without having to call another array method.

Conclusion

Data structures are great because they are fungible — in other words, we can easily convert them from one to another and back again.

If you want a challenge, now take the array of objects that this method returns, and convert it back to an Object! 😎

As always, if you like this story, please clap, share and comment.

Happy coding!

--

--

Elliott

I like learning languages and talking about web development.