Andrew Howard
Andrew Howard

Reputation: 3082

Using forkJoin with async pipe

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>

Upvotes: 1

Views: 878

Answers (2)

Eddy Lin
Eddy Lin

Reputation: 683

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(...);

https://stackblitz.com/edit/rxjs-hid6fz

Upvotes: 1

Dmitry S.
Dmitry S.

Reputation: 1678

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

Upvotes: 4

Related Questions