如何映射到一个 Observable 数组中的多个对象?

How to map to multiple objects within one Observable array?

我正在使用 forkJoin 将两个可观察数组连接在一起:

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$;

在我的映射函数中,我将每个 habit-Observable 的 habitId 映射到我的 status-Observable 的 habitId。

哪个工作正常。问题是,我的 status$-Oberservable 中有 多个对象,我想 映射到一个 habit$-Oberservable 的一个 habitId。如何做到这一点?

而不是使用 find, which returns a single item from an array. You can use filter 到 return 满足指定条件的所有项目的数组:

  map(([habits, statuses]) =>
    habits.map(habit => ({
      ...habit,
      statuses: statuses.filter(s => s.habitId === habit.habitId)
    })))

你快到了。只需使用过滤器而不是查找。 过滤器运行到数组的末尾,并在每个项目上调用它的回调;与 find which 在找到一个后停止相反。

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$;