Search code examples
javascriptobjectdata-structuresecmascript-6assign

javascript Object.assign() without overriding fields


Is there any way to merge two objects, like Object.assign(a, b), but I want the same field in a keeps its origin value (without overriding from b).

a = {x: 1, y: 2}
b = {y: 3, z: 4}

Object.assign(a, b)
// Now we get a = {x: 1, y: 3, z: 4}, so what if I want {x: 1, y: 2, z: 4}?
console.log(a) 

Note: thanks for the efforts from the answers, the key requirements for the question is:

  1. modify a
  2. not too much code
  3. not too slow

Solution

  • Finally I found the perfect solution is lodash.defaults.

    https://lodash.com/docs/4.17.15#defaults

    import _ from 'lodash'
    
    a = {x: 1, y: 2}
    b = {y: 3, z: 4}
    
    _.defaults(a, b)
    
    // Outputs {x:1, y:2, z:4}, perfectly as expected.
    console.log(a)