I have 2 arrays (of objects) and I wish to combine them by id.
Array One:
arrayOne$ = of([{id: 1, name: "Andrew"}, {id: 2, name: "Simon"}]) as Observable<any[]>;
Array Two:
arrayTwo$ = of([{id: 1, age: 22}, {id: 2, age: 56}]) as Observable<any[]>;
So the desired end result will be:
[{id: 1, name: "Andrew", age: 22}, {id: 2, name: "Simon", age: 56}]
I have to get these results via 2 different apis so using the async pipe and forkJoin are required. However I'm now stuck on how to use forkJoin
, do I need to use map
to do this?
So far I have:
TS
combinedResults$ = forkJoin([
this.arrayOne$,
this.arrayTwo$
])
HTML
<div *ngIf="(combinedResults$ | async)?.length !== 0">
<p>Here is the combined list items:</p>
<ul>
<li *ngFor="let item of combinedResults$ | async">
ID: {{item.id}}<br />
Name: {{item.name}}<br />
Age: {{item.age}}
</li>
</ul>
</div>
CodePudding user response:
You're actually on a right track to resolve the issue. Just use map
operator like in the example below:
combinedResults$ = forkJoin([
this.arrayOne$,
this.arrayTwo$
]).pipe(
map((data) =>
data[0].map((item) => {
data[1].forEach((item2) => {
if (item?.id === item2?.id) item = { ...item, ...item2 };
});
return item;
})
)
);
CodePudding user response:
Maybe you can try this
const arrayOne$ = from([{id: 1, name: "Andrew"}, {id: 2, name: "Simon"}]);
const arrayTwo$ = from([{id: 1, age: 22}, {id: 2, age: 56}]);
merge(arrayOne$, arrayTwo$).pipe(
groupBy((k) => k.id),
mergeMap((o$) => o$.pipe(reduce((a,c) => ({...a, ...c})))),
toArray()
).subscribe(...);