首页 > 解决方案 > 如何使用 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......感谢您的帮助!

标签: jsonangularrxjs

解决方案


你可以这样做:

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方法。

实时代码

来自 id 的对象库的 uniq 数组的源


推荐阅读