简体   繁体   English

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

[英]Reduce number of operators in an RxJS mapping expression

I've create an Http request to get json data. 我创建了一个Http请求以获取json数据。 Inside that json - there is an object which has an array. 在该json内部-有一个具有数组的对象。 ( I need that array). (我需要那个数组)。

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

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

      }]
    }
  });

But- the data in the array has a different structure than I actually need. 但是-数组中的数据与我实际需要的结构不同。

I need to map ( name & ISOcode ) to ( name and value ) 我需要将( nameISOcode )映射到( namevalue

This is what I've tried: 这是我尝试过的:

  • Use pluck to extract the inner Array 使用pluck提取内部Array
  • mergeMap the array object to a stream of objects (using of() ) 将数组对象mergeMap到对象流(使用of()
  • using map to transform each item to a desired structure 使用map将每个项目转换为所需的结构
  • using toArray to wrap all to an array ( so I can bind it to a control) 使用toArray将所有内容包装到数组(这样我就可以将其绑定到控件)

Here is the actual code : 这是实际的代码:

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());

The code does work and here is the online demo 该代码可以正常工作, 这是在线演示

Question

It looks like I've complicated it much more than it can be ,Is there a better way of doing it? 看来我已经将其复杂化了很多,是否有更好的方法呢?

This line: mergeMap(a => from(a)) does not make a lot of sense. 这行代码: mergeMap(a => from(a))没有多大意义。 It's almost as if you did [1,2,3].map(v => v) . 几乎就像您做了[1,2,3].map(v => v) You can just remove it. 您可以删除它。

To simplify this you basically need to use Array.map inside Observable.map. 为了简化此操作,您基本上需要在Observable.map中使用Array.map。

Try this: 尝试这个:

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()
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM