我有以下第一个数组(我们称之为组织数组):
[
{
"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
方法来做到这一点?我知道有一个使用 combineLatest
和 forkJoin
似乎都已被弃用。
如有任何帮助,我们将不胜感激。
最佳答案
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/operators
。 rxjs/operators
中的 combineLatest
已弃用,但 rxjs
中的 combineLatest
并未弃用。语法也很重要。 combineLatest(arr1$, arr1$)
已弃用,但 combineLatest([arr1$, arr2$])
并未弃用
关于angular - 当 Angular 中 ID 相等时合并两个可观察量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63699321/