[英]Merge two object arrays by adding object values by same id while also adding unique id
I have a working function which merges two objects arrays with different lengths (source > target under three conditions:我有一个工作 function 合并两个不同长度的对象 arrays (源>目标在三个条件下:
My question is, how can I change this code to be leaner and efficiently?我的问题是,我怎样才能将这段代码更改为更精简和高效? By just looking at the code it seems like it would take a lot of computational resources..只看代码似乎需要大量的计算资源..
I tried to concat the arrays and run them through a while loop but could not figure out a way to differentiate which object belonged to which array..我试图连接 arrays 并通过 while 循环运行它们,但无法找出区分哪个 object 属于哪个数组的方法。
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);
You can make this more efficient by generating an array mapping id
values in source
to their index in the array.您可以通过生成一个数组将source
中的id
值映射到它们在数组中的索引来提高效率。 Then you can iterate over target
, checking whether each objects id
value has an entry in the srcids
array, and if so, updating the corresponding source
x
value, otherwise pushing the object into the source
array:然后你可以遍历target
,检查每个对象的id
值是否在srcids
数组中有一个条目,如果有,更新对应的source
x
值,否则将 object 推入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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.