[英]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
) 我需要将( name
和ISOcode
)映射到( name
和value
)
This is what I've tried: 这是我尝试过的:
pluck
to extract the inner Array 使用pluck
提取内部Array mergeMap
the array object to a stream of objects (using of()
) 将数组对象mergeMap
到对象流(使用of()
) map
to transform each item to a desired structure 使用map
将每个项目转换为所需的结构 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,
}))));
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.