Generate an Object from an Array of Objects

09-15-2021

If you’ve ever had an array of objects, each with a unique value, and would prefer to deal with a single object, this simple solution might help.

Let’s say you received an array of objects, each object in the array has a unique name and value, along with a lot of other information that really isn’t useful. Once you have the array you then need to get the value from each object, you could search the array each time for the object you need and retrieve the value OR you could “reduce” the array of objects down to a single object with just the names and values you need. Let’s look at the later option.

Example Array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const myArray = [
{
name: 'car',
value: 'mercedes',
created_at: 'jan 1, 2000'
},
{
name: 'plane',
value: 'gulfstream g550',
created_at: 'jan 1, 2000'
},
{
name: 'train',
value: 'csx locomotive',
created_at: 'jan 1, 2000'
}
];

Desired result:

1
2
3
4
5
const myObj = {
car: 'mercedes',
plane: 'gulfstream g550',
train: 'csx locomotive'
}

Using the JavaScript reduce() method we can destructure the array and reduce each object to create a final object that is much easier to work with.

The function:

1
const myObj = myArray.reduce((o, key) => ({ ...o, [(key.name)]: key.value }), {});

Breaking it down:

First we’re reducing the array myArray using the .reduce() method. This will execute a function on each element in the array, e.g. our objects, and reduce them down to a single value.

1
myArray.reduce(...)

Next we create a way to track our current and previous values.

o —> previous value
key —> current value

1
myArray.reduce(o, key)

Next we perform our reducing function, this will spread the the previous value object and assign the current value for the given element, e.g. object in the array.

1
myArray.reduce(o, key) => ({ ...o, [(key.name)]: key.value })

Finally we assign our initial value, which is an empty object to start.

1
myArray.reduce(o, key) => ({ ...o, [(key.name)]: key.value }), {});

This function can be extremely handy for making arrays of objects more manageable.