Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge multiple objects inside the same array into one object [duplicate]

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} 
like image 957
error123456789 Avatar asked Dec 18 '14 02:12

error123456789


People also ask

How do you merge an array of objects into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.

How do I combine multiple objects into one?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

How do you concatenate an array of objects?

JavaScript concat() Method : Array ObjectThe concat() method is used to join two or more arrays. Concat does not alter the original arrays, it returns a copy of the same elements combined from the original arrays. arrayname1, arrayname2, ..., arraynameN : Arrays to be joined to an array.


1 Answers

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.

like image 106
thefourtheye Avatar answered Sep 22 '22 22:09

thefourtheye