0

I am using forkJoin to join two observable arrays together:

connect(): Observable<any[]> {
this.userId = this.authService.userId;
this.habits$ = this.habitService.fetchAllById(this.userId);
this.status$ = this.statusService.fetchAll();
this.joined$ = forkJoin([this.habits$, this.status$]).pipe(
  map(([habits, statuses]) =>
    habits.map(habit => ({
      ...habit,
      status: statuses.find(s => s.habitId === habit.habitId)
    })))
);
console.log(this.joined$);

return this.joined$;

In my mapping function I am mapping the habitId from my each habit-Observable to the habitId from my status-Observable.

enter image description here

Which is working fine. The problem is, I have multiple objects in my status$-Oberservable which I want to map to one habitId of one habit$-Oberservable. How to do this?

0

2 Answers 2

1

Instead of using find, which returns a single item from an array. You can use filter to return an array of all items that meet the specified condition:

  map(([habits, statuses]) =>
    habits.map(habit => ({
      ...habit,
      statuses: statuses.filter(s => s.habitId === habit.habitId)
    })))
Sign up to request clarification or add additional context in comments.

Comments

1

You're almost there. just use filter instead of find. filter runs till the end of the array, and invokes its callback on every item; in contrast to find which stops after having found one.

connect(): Observable<any[]> {
this.userId = this.authService.userId;
this.habits$ = this.habitService.fetchAllById(this.userId);
this.status$ = this.statusService.fetchAll();
this.joined$ = forkJoin([this.habits$, this.status$]).pipe(
  map(([habits, statuses]) =>
    habits.map(habit => ({
      ...habit,
      status: statuses.filter(s => s.habitId === habit.habitId)
    })))
);
console.log(this.joined$);

return this.joined$;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.