Search code examples
javascriptobjectlodashjavascript-objects

Shortest Way to Merge JavaScript Objects Based on Path


Anyone know how I could further condense my mergePath method, which merges keys on two objects based on a key/value path? My solution below uses Lodash.

let obj1 = { z: {fields: { a: "200", b: "2" }}}
let obj2 = { z: {fields: { a: "2", b: "20" }}}
let objsPath = "z.fields"

let mergePath = (objsPath, obj1, obj2) => (
  _.set(obj1, objsPath, {..._.get(obj1, objsPath), ..._.get(obj2, objsPath)})
)

Solution

  • You can use _.merge() to copy the path from obj2 to obj2. Then you can return obj1 (I've used the comma operator):

    const obj1 = { z: {fields: { a: "200", b: "2" }}}
    const obj2 = { z: {fields: { a: "2", b: "20" }}}
    const objsPath = "z.fields"
    
    const mergePath = (objsPath, obj1, obj2) => (
      _.merge(_.get(obj1, objsPath), _.get(obj2, objsPath)), obj1
    )
    
    console.log(mergePath(objsPath, obj1, obj2));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>