简体   繁体   English

通过关键Javascript合并两个对象(不覆盖不同的值)

[英]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; 我有一个objetcs数组,每个对象都包含数组。我需要对其进行操作,以使内部数组中的元素(如果不同)被附加,或者如果相同则保持为单个; basically are grouped by type . 基本上按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)? 什么是最有效的方法(可能使用lodash)? I have tried something with foreach and assign but I alwaays end up overriding the inner array... Thank you for help! 我已经尝试过使用foreach和assign进行操作,但是我最终还是会覆盖内部数组...谢谢您的帮助!

You can use _.mergeWith to pass comparison function: 您可以使用_.mergeWith传递比较功能:

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

demo fiddle 演示小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM