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

问题描述

我使用 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$;

在我的映射函数中,我将每个习惯可观察的习惯 ID 映射到状态可观察的习惯 ID。

enter image description here

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

解决方法

而不是使用 find,它从数组中返回单个项目。您可以使用 filter 返回满足指定条件的所有项目的数组:

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

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

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,status: statuses.filter(s => s.habitId === habit.habitId)
    })))
);
console.log(this.joined$);

return this.joined$;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...