Combining multiple objects within the same array into one object

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

      

how can I combine this into one object?

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

      

+15


source to share


2 answers


You can use like this Array.prototype.reduce

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 collects all the keys and their values ​​in each object in result

, which is eventually returned to us as a result.

This check

if (currentObject.hasOwnProperty(key)) {

      



we need to make sure that we don't include all inherited enumerated properties in the result.


If your environment supports then you can do the same in a concise manner like this Object.assign

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));
      

Run codeHide result


+25


source


You can 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 forreduce

details .

+13


source







All Articles