我在Node.js中有两个JSON数组。
var a = [{id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}, {id: 4, name: 'D'}];
var b = [{id: 1, marks: 80}, {id: 2, marks: 30}, {id: 3, marks: 76}];
我想合并这些数组,匹配id
值。请建议一种有效的方法,因为数组包含大约25000
条记录。
期望的输出:
var o = [{id: 1, name: 'A', marks: 80}, {id: 2, name: 'B', marks: 30}, {id: 3, name: 'C', marks: 76}, {id: 4, name: 'D'}];
感谢。
答案 0 :(得分:4)
你应该制作一个索引对象
const indexB = b.reduce( ( result, item ) => {
result[item.id] = item;
return result;
}, {});
var mergedArr = a.map( item => Object.assign( item, indexB[item.id] ) );
在我的基准测试中,下划线方法和我的方法有显着差异:
λ ~/Projects/_tests/performance ◆ time node a.js
node a.js 44.36s user 0.38s system 98% cpu 45.216 total
λ ~/Projects/_tests/performance ◆ time node b.js
node b.js 0.10s user 0.02s system 95% cpu 0.118 total
其中a.js是下划线。
答案 1 :(得分:1)
使用下划线,您可以执行以下操作:
var mergedArr = _.map(v1, function(item){
return _.extend(item, _.findWhere(v2, { id: item.id }));
});
答案 2 :(得分:1)
或类似的东西:
a.map(function (aObj) {
aObj.marks = (b.filter(function (bObj) {
return bObj.id === aObj.id;
}).shift() || {
marks: null
}).marks;
});
console.log(a);
// output:
[ { id: 1, name: 'A', marks: 80 },
{ id: 2, name: 'B', marks: 30 },
{ id: 3, name: 'C', marks: 76 },
{ id: 4, name: 'D', marks: null } ]