Using forkJoin with async pipe

Viewed 25

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?

Stackblitz = https://stackblitz.com/edit/angular-ivy-shlmvh?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.css

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>
1 Answers

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;
        })
      )
    );
Related