Javascript 如何映射到一个可观察阵列中的多个对象?

Javascript 如何映射到一个可观察阵列中的多个对象?,javascript,angular,typescript,rxjs,angular2-observables,Javascript,Angular,Typescript,Rxjs,Angular2 Observables,我使用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$, thi

我使用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$;
connect():可观察

这很好用。问题是,我的状态$-Oberservable中有多个对象,我想映射到一个习惯的一个习惯$-Oberservable。如何执行此操作?

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

map([习惯、状态])=>
习惯图(习惯=>({
…习惯,
statuses:statuses.filter(s=>s.habitId===习惯.habitId)
})))
而不是使用,后者从数组中返回单个项。可以使用返回满足指定条件的所有项的数组:

map([习惯、状态])=>
习惯图(习惯=>({
…习惯,
statuses:statuses.filter(s=>s.habitId===习惯.habitId)
})))

你就快到了。只需使用过滤器而不是查找。 过滤器一直运行到数组的末尾,并对每个项调用其回调;相比之下,在找到一个后,找出哪一个停止

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$;
connect():可观察{
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(
地图([习惯、状态])=>
习惯图(习惯=>({
…习惯,
状态:status.filter(s=>s.habitId===habitId.habitId)
})))
);
console.log(this.joined$);
返回此。已加入$;

就快到了。只需使用过滤器而不是查找。 筛选器一直运行到数组的末尾,并对每个项调用其回调;与查找在找到一项后停止的项相反

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$;
connect():可观察{
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(
地图([习惯、状态])=>
习惯图(习惯=>({
…习惯,
状态:status.filter(s=>s.habitId===habitId.habitId)
})))
);
console.log(this.joined$);
返回此。已加入$;