0

I'm using Object.assign wrong?

I tought it will replace the values, but actually it overwrites them...

For example the 'PEACH' property will be deleted after being assigned.

Isn't it strange? How would you solve this?

Let's save PEACH

var result = Object.assign({
  'first_level': {
    'second_level': {
      'changeme': 'not changed bruh',
      'PEACH': 'PLEASE SAVE ME!'
    }
  },
  'hehe' : 'I will stay here'
}, {
  'first_level': {
    'second_level': {
      'change': 'Changed B]',
      'addme': 'Extra prop'
    }
  },
  'huh' : 'I want to join the party'
});

document.body.innerHTML = '<pre>'+JSON.stringify(result, null, 2)+'</pre>';
KeySee
  • 760
  • 1
  • 12
  • 26

2 Answers2

1

Object.assign does only a shallow Merge. You can use lodash merge for this it does recursively merge the Objects.

Pascal L.
  • 1,261
  • 9
  • 21
0

While Object.assign assign only the first level, you could iterate the entries of the objects and assign either the value or for object the nested assigned values.

function deeperAssign(a, b) {
    Object
        .entries(b)
        .forEach(([k, v]) => a[k] = v && typeof v === 'object'
            ? deeperAssign(a[k] = a[k] || {}, v)
            : v
        );
    return a;
}

var result = deeperAssign(
        { first_level: { second_level: { changeme: 'not changed bruh', PEACH: 'PLEASE SAVE ME!' } }, hehe: 'I will stay here' },
        { first_level: { second_level: { change: 'Changed B]', addme: 'Extra prop' } }, huh: 'I want to join the party' }
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392