0

I want to deeply copy all missing fields into the object shown by the example code below. Is there a quick es6 shortcut for deeply copying the missing properties in the object?

I tried using Object.assign but the problem is that it replaces someKey with the second someKey object, where as I want it to simply copy over all the properties.

Also these objects are just some random demonstrations, let's say the magic code should be property agnostic

const x = {};

const a = { someKey: { first: 1 } };
const b = { someKey: { second: 2 } };
const c = { otherKey: { first: 1 } };

// some magic algorithm to get expected
Object.assign(x, a, b, c); // this doesn't work

const expected = {
  someKey: {
    first: 1,
    second: 2
  },
  otherKey: {
    first: 1
  }
};
dylanpark
  • 129
  • 9

2 Answers2

4

Voit lá. Run snippet for demonstration.

const merge = function(){
  let target = arguments[0];
  Array.prototype.shift.apply(arguments);
  while (arguments[0]) {
    for (let key of Object.keys(arguments[0]))
      if (arguments[0][key] instanceof Object)
        Object.assign(arguments[0][key], merge(target[key], arguments[0][key]));
    Object.assign(target || {}, arguments[0]);
    Array.prototype.shift.apply(arguments);
  }
  return target;
}

const x = {};

const a = { someKey: { first: 1 } };
const b = { someKey: { second: 2 } };
const c = { otherKey: { first: 1 } };

console.log(merge(x,a,b,c));
Attersson
  • 4,755
  • 1
  • 15
  • 29
  • fyi: this doesn't work if you have a really deeply nested object such as `d = { someKey: { random: { word: { first: 2 } } } }` and try to do `merge(x,a,b,c,d)` – dylanpark Aug 30 '18 at 22:45
0

If you want to do a merge on some keys, you'll have to do it by hand Object.assign works on last-in wins so to merge keys you'll want something like the following...

Object.assign({}, a, b, c, {someKey: Object.assign({}, a.someKey, b.someKey)})

the following code can be read as.... merge "A" "B" and "C" together.... Override someKey with a merge of "A.someKey and b.someKey" together.

Shanon Jackson
  • 5,873
  • 1
  • 19
  • 39