我有一个工作函数,可以合并两个不同长度的对象数组(在三种情况下为source> target:
我的问题是,如何更改此代码以使其更精简和有效?仅查看代码,似乎将需要大量的计算资源。.
我试图合并数组并通过while循环运行它们,但找不到找出区分哪个对象属于哪个数组的方法。
let target = [
{ id:1, x: 50 },
{ id:2, x: 30 },
{ id:3, x: 30 }
];
let source = [
{ id:1, x: 30 },
{ id:2, x: 13 },
{ id:4, x: 100 },
{ id:5, x: 5 }
];
let arrayResult = [];
function compute( target, source ) {
for (let i = 0; i < source.length; i++ ) {
let srcObj = source[i];
let tarObj = target.find(d => d.id === srcObj.id)
if (tarObj) {
let result = {
id: srcObj.id,
x: srcObj.x - tarObj.x
}
arrayResult.push(result);
} else {
arrayResult.push(srcObj);
}
}
for( let i = 0; i < target.length; i ++ ) {
let src = target[i];
let tar = arrayResult.find(d => d.id === src.id);
if (!tar){
arrayResult.push(src)
}
}
}
compute(target, source);
console.log(arrayResult);
您可以通过生成将id
中的source
值映射到它们在数组中的索引的数组来提高效率。然后,可以遍历target
,检查每个对象id
值是否在srcids
数组中都有一个条目,如果是,则更新相应的source
x
值,否则将对象推入source
]数组:
let target = [
{ id:1, x: 50 },
{ id:2, x: 30 },
{ id:3, x: 30 }
];
let source = [
{ id:1, x: 30 },
{ id:2, x: 13 },
{ id:4, x: 100 },
{ id:5, x: 5 }
];
const srcids = source.reduce((c, o, i) => {
c[o.id] = i;
return c;
}, []);
target.forEach(o => {
if (srcids[o.id] !== undefined) {
source[srcids[o.id]].x -= o.x;
} else {
source.push(o);
}
});
console.log(source);