Jacob Brauchler
Jacob Brauchler

Reputation: 579

Combining all objects in an array into one

I have an array of objects arr and I want to combine all of the objects in the array into one. There also are repetitive keys in the objects. Is there a way I can do this? Any help would be great.

var arr = [{ a: 1, a: 2 },
{ c: 1, d: 2 },
{ e: 14, f: 20 }];

The output I want is:

var arr = [{ a: 1, 
             a1: 2, 
             c: 1, 
             d: 2, 
             e: 14, 
             f: 20 }];

Upvotes: 0

Views: 255

Answers (3)

Nenad Vracar
Nenad Vracar

Reputation: 122155

You could use reduce() and Object.assign()

var arr = [{ a: 1, b: 2 }, { c: 1, d: 2 }, { e: 14, f: 20 }];

var result  = [arr.reduce((r, o) => Object.assign(r, o), {})];
console.log(result)

Upvotes: 2

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10093

You can simply iterate through the array using for loop and assign all properties of each item to the combined object:

var arr = [{ a: 1, b: 2 },
{ c: 1, d: 2 },
{ e: 14, f: 20 }];

var combinedObj = {};

for( var i = 0; i < arr.length; i++ )
{
  var item = arr[i];
  for(var key in item )
  {
    combinedObj[key] = item[key];
  }//for()
}//for

console.log( combinedObj );

Upvotes: 2

tymeJV
tymeJV

Reputation: 104805

Assuming all the keys are unique and you don't want to check, use reduce

var combinedKeys = arr.reduce(function(a, item) {
    Object.keys(item).map(function(key) {
        a[key] = item[key];
    });

    return a;
}, {});

var singleArrayOfCombinedKeys = [combinedKeys]; //[Object  a: 1b: 2c: 1d: 2e: 14f: 20__proto__: Object]

Upvotes: 2

Related Questions