be2021
be2021

Reputation: 49

How to map two Oberservable arrays based on a value?

I have two observable arrays.

habits$: Observable<Habit[]>;
status$: Observable<Status[]>;

The habit has the following structure:

export interface Habit {
  habitId: number;
  name: string;
  repeatVal: number;
  notification: string;
  color: string;
  question: string;
  id: number;
}

The status array has the habitId, date and status as keys.

I want to merge both habits$ and status$ into one Observable array based on the habitId attribute present in both of them.

I have done some research and a combination of mergeMap() and forkJoin() seems to be the way to go, like shown here Combine multiple observable arrays into new object array

But I can't figure out a syntax that will work for me.

This is how my code looks at the moment:

ngOnInit() {
this.habits$ = this.habitService.fetchAllById(this.authService.userId);
console.log(this.habits$);
this.status$ = this.statusService.fetchAll();
this.habits$.pipe(
  mergeMap(habits => {
  this.status$ = this.statusService.fetchAll().filter(status => status.habitId == habits.habitId);
}));
console.log(this.joined$);}

Upvotes: 0

Views: 689

Answers (1)

Moshezauros
Moshezauros

Reputation: 2593

I would use forkJoin in the following fashion:

ngOnInit() {
  forkJoin([
    this.habitService.fetchAllById(this.authService.userId),
    this.status$ = this.statusService.fetchAll()
  ]).subscribe(([habits, statuses]) => {
    this.joined = habits.map(habit => ({
      ...statuses.find(t => t.habitId === habit.habitId),
      ...habit 
    }));
  });
}

see simple demo

Upvotes: 2

Related Questions