通过添加相同 id 的对象值同时添加唯一 id 来合并两个对象数组
Merge two object arrays by adding object values by same id while also adding unique id
我有一个工作函数,它合并两个不同长度的对象数组(源>目标在三种情况下:
- 包含目标数组中具有唯一 ID 的对象
- 包括源数组中具有唯一 ID 的对象
- 通过从源值中减去目标值来包含具有重复 ID 的对象
我的问题是,如何更改此代码以使其更精简和高效?
光看代码好像会占用很多计算资源..
我试图通过 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);
您可以生成一个数组,将 source
中的 id
值映射到它们在数组中的索引,从而提高效率。然后你可以遍历 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);
我有一个工作函数,它合并两个不同长度的对象数组(源>目标在三种情况下:
- 包含目标数组中具有唯一 ID 的对象
- 包括源数组中具有唯一 ID 的对象
- 通过从源值中减去目标值来包含具有重复 ID 的对象
我的问题是,如何更改此代码以使其更精简和高效? 光看代码好像会占用很多计算资源..
我试图通过 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);
您可以生成一个数组,将 source
中的 id
值映射到它们在数组中的索引,从而提高效率。然后你可以遍历 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);