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

时间:2017-09-23 06:12:53

标签: javascript arrays node.js object lodash

我想将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
});

结果:

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

它看起来很愚蠢吗?有没有其他方法可以做到这一点? 谢谢你的阅读。

2 个答案:

答案 0 :(得分: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 }
];

let result = arr1.map((e) => {
    for(let element of arr2){
        if(e.a == element.a) Object.assign(e, element);
    }
    return e;
});
console.log(result);

答案 1 :(得分:2)

使用lodash链来concat数组,group类似对象,然后merge每个组到一个对象:



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>
&#13;
&#13;
&#13;

使用ES6,您可以使用Array#reduce收集Map中的类似对象,然后获取Map#values迭代器,并使用spread syntax转换为数组:

&#13;
&#13;
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(o.a, Object.assign(m.get(o.a) || {}, 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);
&#13;
&#13;
&#13;