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

published: 10 Jun 2022

2 min read

How to convert an array of objects to an object 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() method along with spread operator syntax (...).

The Object.assign() method was introduced in ES6 (ESMAScript 2015), and it copies all enumerable own properties of one or more source objects to a target object, and returns the target object.

Her is an example:

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:

// 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 to learn more about different ways to merge objects in JavaScript. To flatten an array in JavaScript, check out this article.

How to convert an array of objects to an object in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array