【问题标题】:how to flatten the nested array in rxjs如何展平 rxjs 中的嵌套数组
【发布时间】:2022-01-19 15:57:09
【问题描述】:

我正在使用 forkJoin 订阅多个内部 observable。如何将嵌套数组扁平化为单级数组。

const x$ = of([1, 2, 3, 4]);
const y$ = of([2, 4]);

x$.pipe(
  switchMap((t) => {
    const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
    return forkJoin(innerArr$);
  })
).subscribe(console.log);

游乐场链接:Rxjs stackblitz

预期输出:

[2,4,4,8,6,12,8,16]

【问题讨论】:

    标签: rxjs rxjs5 rxjs6 rxjs-observables rxjs-pipeable-operators


    【解决方案1】:

    你可以试试这个

    x$.pipe(
      switchMap((t) => {
        const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
        return forkJoin(innerArr$);
      }),
      mergeMap((aa) => from(aa).pipe(mergeMap((a) => a)))
    ).subscribe(console.log);
    

    这里的关键是

    • mergeMap 实际上是一个扁平化的 Observable 类对象(实际上 mergeMap 以前称为flatMap)
    • Array 被视为 Observable,因为它实际上可以表示数据流,这就是 Observable 的含义

    【讨论】:

      【解决方案2】:

      如果您想要一个数字流,请 +1 @Picci 的回答。

      如果您想以单个数组结束,您可以在订阅中展平结果:

      x$.pipe(
        switchMap((t) => {
          const innerArr$ = t.map((z) => y$.pipe(map((_) => _.map((y) => y * z))));
          return forkJoin(innerArr$);
        })
      )
      .subscribe((res) => {
        console.log([].concat.apply([], res));
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 2012-11-21
        • 2014-05-28
        • 2015-10-29
        • 2019-03-03
        • 2021-06-03
        相关资源
        最近更新 更多