# How to convert an array of objects to an object in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Nov 24, 2020. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-convert-array-of-objects-to-object

> Learn how to convert an array of objects to a single object with all key-value pairs in JavaScript.

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the [Object.assign()](https://attacomsian.com/blog/javascript-object-assign) method along with spread operator syntax (`...`).

The `Object.assign()` method was introduced in ES6 (ESMAScript 2015), and it [copies](https://attacomsian.com/blog/javascript-merge-objects#objectassign-method) all enumerable own properties of one or more source objects to a target object, and returns the target object.

Her is an example:

```javascript
const fruits = [{ apple: '?' }, { banana: '?' }, { orange: '?' }];

// Merge all array objects into single object
const allFruits = Object.assign({}, ...fruits);

// Print fruits
console.log(allFruits);

// { apple: '?', banana: '?', orange: '?' }
```

Note that the properties are overwritten by the objects that have the same properties later in the array:

```javascript
// Array with duplicate object keys
const fruits = [{ apple: '?' }, { banana: '?' }, { orange: '?' }, { apple: '?' }];

// Merge all array objects into single object
const allFruits = Object.assign({}, ...fruits);

// Print fruits
console.log(allFruits);

// { apple: '?', banana: '?', orange: '?' }
```

Take a look at [this article](https://attacomsian.com/blog/javascript-merge-objects) to learn more about different ways to merge objects in JavaScript. To flatten an array in JavaScript, check out [this article](https://attacomsian.com/blog/javascript-flatten-array).
