如何在 RxJS 的 GroupBy 中使用分组键,

How to use grouping key in GroupBy in RxJS,

我的结构 return 由 API

编辑

这是签名

methodApi(): Observable(Array<MyClass>)

这是数据

{ id: 1, name: 'Red', parentId: null }
{ id: 2, name: 'Apple', parentId: 1 }
others

我想按parentId分组

methodApi()
.pipe(groupby((x: MyClass[] => ...))) // THERE
.subscribe(x => console.log(x));

MethodApi return Observable,在 'groupby' 方法中作为输入参数我有数组,所以我不能引用 parentId属性。当我将输入参数更改为 MyClass 时,出现编译错误。

如何解决这个分组? 我使用 Angular 9.0 和 RxJS 6.5.5

您必须使用 from 从您的数组创建另一个可观察流,然后使用 groupBy 然后将其转换回结果数组:

methodApi().pipe(
  concatMap((result) => from(result)),
  groupBy((item) => item.parentId),
  mergeMap(group => group.pipe(toArray()))
).subscribe(x => console.log(x));

example stack

您也可以使用 mergeAll:

methodApi().pipe(
  mergeAll(),
  groupBy((item) => item.parentId),
  mergeMap(group => group.pipe(toArray()))
).subscribe(x => console.log(x));

example stack

使用 groupBy 运算符应该很简单,如下所示,

methodApi().pipe(
  groupBy((item) => item.parentId),
  mergeMap(group => group.pipe(toArray()))
).subscribe(console.log) // should get you an array with groupBy parentId

这不是 RxJs group by operator 的工作方式。 RxJs 运算符对流发出的对象进行分组,您正在寻找对流发出的数组中的项目进行分组。您需要一个适用于数组而不是可观察对象的函数分组。您可以使用简单的 reduce 将它们全部分组到一个以 parentId 作为键的对象。

methodApi()
.pipe(map(results => results.reduce(
  (group, item) => {
    if (group[item.parentId]) {
      group[item.parentId].push(item);
    } else {
      group[item.parentId] = [item];
    }
    return group;
  }, {})
)).subscribe(group => {});