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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.