繁体   English   中英

比较两个arrays的对象,合并部分字段

[英]Compare two arrays of objects and merge some fields

我正在使用 Angular 和 RxJs,我有两个 arrays 对象。 如果第二个数组具有相同值的字段(所有四个字段都具有不同的名称),我需要更改第一个数组的一个特定字段。 我用嵌套循环做到了,但我需要找到更好的解决方案,我的代码在下面

我的解决方案有效,但不是最好的,因为 arrays 可能非常大 - 因此代码运行速度会很慢。 如果每个数组中有 1000 个项目,那将是 1000000 次迭代——这就是为什么我需要找到更好的解决方案。 我得到了使用多个连续循环的建议,但我真的不知道如何在这里使用它

this.api
  .getFirstArray()
  .pipe(
    mergeMap((firstArray) =>
      this._secondApi.getSecondArray().pipe(
        map((secondArray) => {
          for (const item2 of secondArray) {
            for (const item1 of firstArray) {
              if (item1.someField === item2.otherField)
                item1.someOtherField = item2.anotherField;
            }
          }

          return firstArray;
        }),
      ),
    ),
  )
  .subscribe((value) => {
    this.gridApi?.setRowData(value);
  });

所以例如我的数据是

 firstArray: [
    { id: 445; name: 'test' },
    { id: 4355; name: 'test1' },
    { id: 234_234; name: 'test2' },
  ];

secondArray: [
    { firstName: 'test3'; newId: 445 },
    { firstName: 'test5'; newId: 2 },
    { firstName: 'test6'; newId: 234_234 },
  ];

结果应该是

result: [{ id: 445; name: 'test3' }, { id: 4355; name: 'test1' }, { id: 234_234; name: 'test6' }];

注意:第一个数组对象的 ID 可能会重复 - 所有对象名称都需要更新

这是您的问题的工作示例,可能会对您有所帮助。

 let firstArray = [ { id: 445, name: 'test' }, { id: 4355, name: 'test1' }, { id: '234_234', name: 'test2' }, ]; let secondArray = [ { firstName: 'test3', newId: 445 }, { firstName: 'test5', newId: 2 }, { firstName: 'test6', newId: '234_234' }, ]; secondArray.forEach(sec => { let see = firstArray.findIndex(first => first.id === sec.newId); if (see > -1) { firstArray[see].name = sec.firstName } }) console.log(firstArray)

您最终仍然会遇到 O(N²) 复杂性(他想避免两个嵌套循环)。

相反,您可以使用 map

const firstArray = [
  { id: 445, name: 'test' },
  { id: 4355, name: 'test1' },
  { id: '234_234', name: 'test2' },
];

const secondArray = [
  { firstName: 'test3', newId: 445 },
  { firstName: 'test5', newId: 2 },
  { firstName: 'test6', newId: '234_234' },
];

const secondMap = new Map();

secondArray.forEach((item) => {
  secondMap.set(item.newId, item.firstName);
});

for (const item of firstArray) {
  if (secondMap.has(item.id)) {
    item.name = secondMap.get(item.id);
  }
}

console.log(firstArray)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM