通过相同的ID添加对象值,同时还添加唯一的ID合并两个对象数组

问题描述 投票:1回答:1

我有一个工作函数,可以合并两个不同长度的对象数组(在三种情况下为source> target:

  1. 包括目标数组中具有唯一ID的对象
  2. 包括源数组中具有唯一ID的对象
  3. 通过从源值中减去目标值来包含具有重复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);
javascript arrays array-merge
1个回答
0
投票

您可以通过生成将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);
© www.soinside.com 2019 - 2024. All rights reserved.