Search code examples
javascriptlodash

merge two objects by key Javascript (without overriding different values)


I have an array of objetcs whith each object containing arrays.I need to manipulate it so that element within the inner arrays are appended if different or kept as single if the same; basically are grouped by type. It's a bit hard to explain so I give you an example. Here is the array I have:

let array1 = [{
      1: [{
         id: "aaaa",
         name: 'name1',
         type: 1
       }],
      2: [{
         id: 'bbbb',
         name: 'name2',
         type: 2
       }],
      3: [{
         id: "ccc",
         name: 'name3',
         type: 3
      }] 
     },
     {1: [{
         id: "aaaa",
         name: 'name1',
         type: 1
       }],
      2: [{
         id: 'bbbb',
         name: 'name2',
         type: 2
       }],
      3: [{
        id: "dddd",
        name: 'name4',
        type: 3
       }], 
     };

And I would like to get something like the following object:

        let result = {
      1: [
        {
          id: "aaaa",
          name: 'name1',
          type: 1
        }],
      2: [{
          id: 'bbbb',
          name: 'name2',
          type: 2
        }],
      3: [{
          id: "cccc",
          name: 'name3',
          type: 3
        },
        {
          id: "dddd",
          name: 'name4',
          type: 3
        }
      ]
    }

what would be the most efficient way to do this (possibly using lodash)? I have tried something with foreach and assign but I alwaays end up overriding the inner array... Thank you for help!


Solution

  • You can use _.mergeWith to pass comparison function:

    var result = array1.shift();
    _.mergeWith(result, ...array1, function(a, b) {
        return _.isEqual(a, b) ? a : _.concat(a, b);
    });
    console.log(result);
    

    demo fiddle