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.