简体   繁体   English

合并具有相同键的2个对象,两个数组中的值

[英]Merge 2 object with same key, value from 2 array

I want to merge 2 object with same key, value from 2 array, something like this: 我想合并具有相同键,2数组中的值的2个对象,像这样:

var arr1 = [
    { a: "a", 1: 1, 2: 2 },
    { a: "b", 1: 1, 2: 3 }
];

var arr2 = [
    { a: "a", 3: 123 },
    { a: "b", 3: 4411 }
];

var arr3 = _.map(arr1, function(a1) {
    var a3 = {};

    _.map(arr2, function(a2) {
        if (a1.a == a2.a) {
            a3 = _.extend(a1, a2);
        }
    })

    return a3
});

result: 结果:

arr3 = [ 
  { '1': 1, '2': 2, '3': 123, a: 'a' },
  { '1': 1, '2': 3, '3': 4411, a: 'b' } 
]

Does it look stupid? 看起来很蠢吗? Are there any others ways to do this? 还有其他方法吗? Thanks for reading. 谢谢阅读。

Use a lodash chain to concat the arrays, group similar objects, and then merge each group to a single object: 使用lodash链Concat的阵列, 类似的对象,然后合并各组的单个对象:

 var arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }]; var arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }]; var result = _(arr1) .concat(arr2) // concat the 2nd array .groupBy('a') // group by the identical key .map(_.spread(_.curry(_.merge, {}))) // left currey merge to to create a new empty object, and spread the group as parameters .value(); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

With ES6 you can use Array#reduce to collect the similar objects in a Map , then get the Map#values iterator, and use the spread syntax to convert to an array: 使用ES6,您可以使用Array#reduce收集Map中的相似对象,然后获取Map#values迭代器,并使用传播语法将其转换为数组:

 const arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }]; const arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }]; const result = [...arr1.concat(arr2) // concat the arrays .reduce((m, o) => m.set(oa, Object.assign(m.get(oa) || {}, o)), // use a map to collect similar objects new Map() ).values()]; // get the values iterator of the map, and spread into a new array console.log(result); 

you can do 你可以做

 var arr1 = [ { a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 } ]; var arr2 = [ { a: "a", 3: 123 }, { a: "b", 3: 4411 } ]; let result = arr1.map((e) => { for(let element of arr2){ if(ea == element.a) Object.assign(e, element); } return e; }); console.log(result); 

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

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