json - 如何使用 RxJS 进行 groupBy 并在特定数组中获取结果?
问题描述
我有一个具有这些属性的对象:
{
title: 'Test',
places: [
{
id: 1,
longitude: 48.8469511,
latitute: 2.3077989,
address: 'Pont de Bir-Hakeim',
city: {name: 'Paris', id: 1}
},
{
id: 2,
longitude: 48.855225,
latitute: 2.288048,
address: 'Palais-Musée Galliera, 10 avenue Pierre-1er-de-Serbie',
city: {name: 'Paris', id: 1}
},
{
id: 3,
longitude: 50.8283315,
latitute: -115.2608429,
address: 'Fortress Moutain',
city: {name: 'Calgary', id: 2}
}
]
}
这是我想要的结果:
[
{
id: 1,
name: 'Paris'
},
{
id: 2,
name: 'Calgary'
},
]
我怎样才能通过使用来实现groupBy
map
reduce
呢?这是我尝试过的:
return from(movie.places).pipe(
groupBy(place => place.city.name),
mergeMap(place => place.pipe(map(obj => obj.city.name))),
toArray()
);
哪个生产:
['Paris', 'Paris', 'Calgary']
我对如何一起使用groupBy
, map
, mergeMap
,不是很清楚toArray
......感谢您的帮助!
解决方案
你可以这样做:
source$.pipe(
map(state => state.places), // transform your source object to list of places.
// Transform your list of place by list of city, then reduce it for unduplicate it.
map(state => state.map(e => e.city).reduce( ( acc, cur ) => [
...acc.filter( ( obj ) => obj.id !== cur.id ), cur
], [] ))
).subscribe(console.log);
我已拆分为两个不同的地图以保持我的代码清晰,如果您愿意,您可以轻松地将其合并到单个地图。
这段代码对于非常大的数据集合也不安全,如果你想有效地处理大数据,更喜欢normalizr方法。
推荐阅读
- quarkus - 如何获取当前的 HttpRequest quarkus?
- sql - SQL - 在同一查询上下文中引用列值
- mysql - Laravel 多对多合并 Pivot?
- amazon-web-services - 有没有使用相同 terraform 脚本的跨账户部署的好例子?
- python - 加载页面时出现 Selenium ChromeDriver 错误
- android - 每当我触摸并按住屏幕上的几乎任何元素时,都会出现灰色框,其中包含视图标签。我怎样才能删除这个?
- c++ - 二叉树和处理器(C++ Codeforces 问题)
- python - 使用列表值来确定哪个是父级,哪个是子级
- video - mp4 视频使用 mplayer 在命令行中显示,但不在脚本中
- python - 将 matplotlib 的流图坐标转换为 numpy 坐标