Search code examples
javascriptlodash

Javascript lodash merge array items by first item


there is a way for merge array items by first item

_.merge({a: 1, c: [{y: 8}, {z: 9}]}, {b: 0, c: [{x: 5}]})

Result:

{
   "a": 1,
   "c": [
      {
         "y": 8,
         "x": 5
      },
      {
         "z": 9
      }
   ],
   "b": 0
}

what i want:

{
   "a": 1,
   "c": [
      {
         "y": 8,
         "x": 5
      },
      {
         "z": 9,
         "x": 5 // <-------------------------
      }
   ],
   "b": 0
}

I want merge a source object by another used like a model. In case of array the model define only the first item of the collection and the source object should reflect the first model item into all the collection items.


Solution

  • I wouldn't actually do it, as it might be very confusing (especially when you've got an array with more than 1 item).

    You can use _.mergeWith(), and manually iterate and merge array items.

    const mrg = (o1, o2) => _.mergeWith(
      o1, o2,
      (a, b) => _.isArray(a) && _.isArray(b) ?
        a.map((item, i) => mrg(item, b[Math.min(i, b.length - 1)]))
        : 
        undefined
    )
    
    const result = mrg({a: 1, c: [{y: 8}, {z: 9}]}, {b: 0, c: [{x: 5}]})
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>