---
title: Generate an Object from an Array of Objects
description: If you've ever had an array of objects, each with a unique value and wanted to deal with a single object this simple solution might help.
date: 2021-09-15
tags: JavaScript
source: https://brianchildress.co/blog/generate-object-from-array-of-objects
---

# Generate an Object from an Array of Objects

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:_**
```js
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:_**

```js
  const myObj = {
    car: 'mercedes',
    plane: 'gulfstream g550',
    train: 'csx locomotive'
  }
```

Using the JavaScript [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) method we can [destructure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) the array and reduce each object to create a final object that is much easier to work with.

**_The function:_**

```js
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.

```js
myArray.reduce(...)
```

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

`o` ---> previous value
`key` ---> current value

```js
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.

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

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

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

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