减少 RxJS 映射表达式中的运算符数量

Reduce number of operators in an RxJS mapping expression

我创建了一个 Http 请求来获取 json 数据。在那个 json 里面 - 有一个有数组的对象。 (我需要那个数组)。

fromDb$ = of({
    Result: {
      Countries: [{      <--wanted array
        ISOCode: 1,
        Name: 'aaa'

      }, {
        ISOCode: 2,
        Name: 'bbb'

      }]
    }
  });

但是-数组中的数据与我实际需要的结构不同。

我需要将 (name &ISOcode) 映射到 (namevalue )

这是我试过的:

这是实际代码:

this.data = this.fromDb$.pipe(pluck<PtCountries, Array<Country>>('Result', 'Countries'), 
                                mergeMap(a => from(a)),
                                map((c: Country) => ({
                                  name: c.Name,
                                  value: c.ISOCode,
                                })),
                              toArray());

代码确实有效 here is the online demo

问题

看起来我把它复杂化了很多,有没有更好的方法呢?

这一行:mergeMap(a => from(a)) 没有多大意义。这几乎就像你做了 [1,2,3].map(v => v)。你可以删除它。

为了简化这一点,您基本上需要在 Observable.map.

中使用 Array.map

试试这个:

this.data = this.fromDb$.pipe(pluck<PtCountries, Array<Country>>('Result', 'Countries'),
  map((countries: Country[]) => countries.map(country => ({
    name: country.Name,
    value: country.ISOCode,
}))));

Live demo

    this.data = this.fromDb$.pipe(
        mergeMap(object => object.Result.Countries),
        map(country => ({ name: country.Name, value: country.ISOCode })),
        toArray()
    );