Languages
[Edit]
EN

JavaScript - merge multiple objects inside the same array into one object

0 points
Created by:
Brandy-Mccabe
754

In this article, we would like to show you how to merge multiple objects inside the same array into one object in JavaScript.

1. Using reduce() with Object assign()

In this example, we use reduce() method with Object assign() as the reducer function to merge all objects inside array together.

// ONLINE-RUNNER:browser;

const array = [
    { a: 1, b: 2 },
    { c: 3, d: 4 },
    { e: 5, f: 6 },
];

const result = array.reduce((target, source) => Object.assign(target, source), {});

console.log(JSON.stringify(result, null, 4));  // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

Note:

The Object.assign() method copies all enumerable own properties from source object to a target object. It returns the modified target object.

2. Using Object assign() with spread syntax (...

In this solution, we use assign() method with spread syntax (...) to merge all objects inside the same array into one object.

// ONLINE-RUNNER:browser;

const array = [
    { a: 1, b: 2 },
    { c: 3, d: 4 },
    { e: 5, f: 6 },
];

const result = Object.assign({}, ...array);

console.log(JSON.stringify(result, null, 4)); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

3. Solution for older versions of JavaScript

In this solution, we use reduce() method to gather all the keys and their values from every object in the resultObject. hasOwnProperty() method is used to check that we are not including all the inherited enumerable properties in the result.

// ONLINE-RUNNER:browser;

var array = [
    { a: 1, b: 2 },
    { c: 3, d: 4 },
    { e: 5, f: 6 },
];

var result = array.reduce(function(resultObject, currentObject) {
    for (var key in currentObject) {
        if (currentObject.hasOwnProperty(key)) {
            resultObject[key] = currentObject[key];
        }
    }
    return resultObject;
}, {});

console.log(JSON.stringify(result, null, 4)); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

 

See also

  1. JavaScript - ECMAScript / ES versions and features

References

  1. Object.assign() - JavaScript | MDN
  2. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - merge multiple objects from the same array into one object
  2. JavaScript - merge all objects inside the same array into one object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join