减少 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
) 映射到 (name
和 value
)
这是我试过的:
- 使用
pluck
提取内部数组
mergeMap
数组对象到对象流(使用of()
)
- 使用
map
将每个项目转换为所需的结构
- 使用
toArray
将所有内容包装到一个数组中(这样我就可以将它绑定到一个控件上)
这是实际代码:
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,
}))));
this.data = this.fromDb$.pipe(
mergeMap(object => object.Result.Countries),
map(country => ({ name: country.Name, value: country.ISOCode })),
toArray()
);
我创建了一个 Http 请求来获取 json 数据。在那个 json 里面 - 有一个有数组的对象。 (我需要那个数组)。
fromDb$ = of({
Result: {
Countries: [{ <--wanted array
ISOCode: 1,
Name: 'aaa'
}, {
ISOCode: 2,
Name: 'bbb'
}]
}
});
但是-数组中的数据与我实际需要的结构不同。
我需要将 (name
&ISOcode
) 映射到 (name
和 value
)
这是我试过的:
- 使用
pluck
提取内部数组 mergeMap
数组对象到对象流(使用of()
)- 使用
map
将每个项目转换为所需的结构 - 使用
toArray
将所有内容包装到一个数组中(这样我就可以将它绑定到一个控件上)
这是实际代码:
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,
}))));
this.data = this.fromDb$.pipe(
mergeMap(object => object.Result.Countries),
map(country => ({ name: country.Name, value: country.ISOCode })),
toArray()
);