angular - 当 Angular 中 ID 相等时合并两个可观察量

标签 angular rxjs

我有以下第一个数组(我们称之为组织数组):

[
  {
    "name": "Apple",
    "id": "org1"
  },
  {
    "name": "Microsoft",
    "id": "org2"
  }
]

第二个数组是(我们称之为单位数组):

[
  {
    "organisation_id": "org1",
    "id": "unitId1"
  },
  {
    "organisation_id": "org30",
    "id": "UnitId2"
  }
]

我希望输出如下所示:

[
  {
    "name": "Apple",
    "id": "org1",
    "units": [
        {
          "organisation_id": "org1",
          "id": "unitId1"
        }
      ]
  },
  {
    "name": "Microsoft",
    "id": "org2",
    "units": []
  }
]

我想将这两个数组(每个对象)组合成一个对象数组,并在 id === Organization_id 时创建一个 units 属性。当我做这样的事情时,这有效:

const combOrgUnit: OrganisationAndUnit[] = [];

this.organisations.subscribe(orgList => {
  this.units.subscribe(unitList => {
    for (const org of orgList) {
      const tempComb: OrganisationAndUnit = {organisation: undefined, units: []};
      const tempUnit: Unit[] = [];
      tempComb.organisation = org;
      for (const unit of unitList) {
        if (org.id === unit.organisation_id) {
          tempUnit.push(unit);
          tempComb.units = tempUnit;
        }
      }
      combOrgUnit.push(tempComb);
    }
    console.log(combOrgUnit);
  });
});

这看起来像是一种草率的检查条件的方法,是否有更多的 rxjs 方法来做到这一点?我知道有一个使用 combineLatestforkJoin 似乎都已被弃用。

如有任何帮助,我们将不胜感激。

最佳答案

const arr1$ = of([
  {
    "name": "Apple",
    "id": "org1"
  },
  {
    "name": "Microsoft",
    "id": "org2"
  }
])
const arr2$ = of([
  {
    "organisation_id": "org1",
    "id": "unitId1"
  },
  {
    "organisation_id": "org30",
    "id": "UnitId2"
  }
]);

const arr3$ = combineLatest([arr1$, arr2$]).pipe(
  map(([arr1, arr2]) => {
    return arr1.map( item => ({
        name: item.name,
        id: item.id,
        units: arr2.filter(
          unit => unit.organisation_id === item.id
        )
      }))
    }
  )
)

注意:请注意从 rxjs 导入 combineLatest rxjs/operatorsrxjs/operators 中的 combineLatest 已弃用,但 rxjs 中的 combineLatest 并未弃用。语法也很重要。 combineLatest(arr1$, arr1$) 已弃用,但 combineLatest([arr1$, arr2$]) 并未弃用

关于angular - 当 Angular 中 ID 相等时合并两个可观察量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63699321/

相关文章:

javascript - 如何使用 Angular Material 在下拉列表中创建 TreeView ?

angularjs - 缓存和延迟数据检索的可观察模式

javascript - 继续跟踪 RxJs 中的 "original"项目

javascript - 你如何使用 RXjs 随着时间的推移发出一组值?

system.reactive - Rx 如何合并可观察对象,并且仅在指定时间范围内提供了 onnext 时才触发

angular - 使用 --watch 依次运行两个 Angular CLI 任务

angular - 如何在使用 Renderer2 创建的元素上设置指令和属性绑定(bind)

javascript - 如何在 Firefox Addon 开发中使用 RxJs?

Angular 2 - 页面加载时有许多历史条目

angular - 如何在 FormArray( react 形式)中使用 mat-autocomplete(Angular Material Autocomplete)