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

how can i merge this into one obj?

//mergedObj = {a:1, b:2, c:3, d:4, e:5, f:6}
0

2 Answers 2

174

If your environment supports Object.assign, then you can do the same in a succinct way like this

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

console.log(arrObj.reduce(function(result, current) {
  return Object.assign(result, current);
}, {}));

// If you prefer arrow functions, you can make it a one-liner ;-)
console.log(arrObj.reduce(((r, c) => Object.assign(r, c)), {}));

// Thanks Spen from the comments. You can use the spread operator with assign
console.log(Object.assign({}, ...arrObj));


ES5 solution:

You can use Array.prototype.reduce like this

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

console.log(resultObject);
# { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

This solution, simply gathers all the keys and their values in every object in the result, which is finally returned to us as the result.

This check

if (currentObject.hasOwnProperty(key)) {

is necessary to make sure that we are not including all the inherited enumerable properties in the result.

Sign up to request clarification or add additional context in comments.

5 Comments

We can avoid using reduce completely by invoking Object.assign with apply. Object.assign.apply( null, objects );
Or, use the spread operator: Object.assign( ...arrObj )
@Spen Thanks. I have included your suggestion as well in the answer.
@Spen FYI, Object.assign(...arrObj) mutates the first element of the array. So, should be: Object.assign({}, ...arrObj)
Object.assign({}, [{one: 1},{two: 2}, {three:3}]) ,, i find this helpful, and very works on me.
25

You could use reduce for an elegant solution:

arrObj.reduce(function(acc, x) {
    for (var key in x) acc[key] = x[key];
    return acc;
}, {});

See MDN docs for reduce for more information.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.