簡體   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