0

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 }];
4
  • 2 minutes solution: jsfiddle.net/osp5fawq Commented Jul 7, 2016 at 15:21
  • Do you mean that your output is supposed to have a, and b, and not a, and a, right? Commented Jul 7, 2016 at 15:26
  • I have multiple keys that are the same and want to rename them if there are duplicates. Commented Jul 7, 2016 at 15:28
  • @KevBot yes that is what I want in the output, basically Commented Jul 7, 2016 at 15:47

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

7 Comments

This is a great answer, So how would I approach this issue if I do have keys that are not unique but still want them included.
@JacobBrauchler -- Depends on the outcome you want - are you looking to sum the numbers up?
no I I do not want to sum them up I want the object to look like the output in my question, I was just using the numbers as an example.
@JacobBrauchler -- Well if you have the same key twice, it can't be in the structure you want. Keys have to be unique. You can combine the values, or create an array of values.
is there a way that if it isn't unique you just rename it?
|
2

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

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.