【问题标题】:GroupBy an RxJS Observable into key-valuesGroupBy 将一个 RxJS Observable 转化为键值
【发布时间】:2020-11-17 13:52:51
【问题描述】:

我有以下 Observable 类型的条目:

[{
   "id": 1,
   "name": "Testuser 1",
   "projectAccess": Role,
}] 

.json

Role {
id: string;
name:string;
}

所以要求就像有一个数组,其中用户是分组角色,我想在通用自动完成组件中作为组条目传递

  return data:
  [{
  manager, [{"1", "Frank"}, {"3", "Seba"}]
  },
  {employee, [{"2", "Simi"}]
  },]

任何帮助将不胜感激。谢谢您

【问题讨论】:

    标签: angular autocomplete rxjs rxjs-observables


    【解决方案1】:

    为了实现 groupby 功能,您必须实现自己的 groupby 功能。

    由于管道(map())组合,该函数与使用可观察对象和简单数组没有区别

    为了达到这个问题,这个问题与question 非常相似 此处列出的算法会生成一个对象,其中对象的键是分组属性,值是列表中的出现次数。

    示例代码

    私有 testUser:Observable

    this.testuser.pipe(map((value)=>{
       return groupBy(value);
    }))
    
    
    
    groupBy(user[]) {
      let groupped=xs.reduce(function(rv, x) {
        (rv[x.ProjectAccess.Name] = rv[x.ProjectAccess.Name] || []).push(x);
        return rv;
      }, {});
    
      let returnList=[];
    
      for(let i in groupped){
       returnList.push({role:i,value:groupped[i]})
      }
    };
    

    【讨论】:

      【解决方案2】:

      Rxjs reduce 应该适用

      const {of} = rxjs;
      const {reduce} = rxjs.operators;
      
      const data = [ {
          id: 1,
          name: 'Testuser 1',
          projectAccess: {id: 1, name: 'manager'},
      } ];
      
      of(data).pipe(
          reduce((acc, _data) => {
            for (let item of _data) {
              if (acc[item.projectAccess.name]) {
                acc[item.projectAccess.name] = [...acc[item.projectAccess.name], {[item.id]: item.name}];
              } else {
                acc[item.projectAccess.name] = [{[item.id]: item.name}];
              }
            }
            return acc;
        }, {}),
      ).subscribe(console.log);
      <script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

      【讨论】:

        猜你喜欢
        • 2018-10-24
        • 2020-12-01
        • 2021-05-24
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2016-12-25
        • 2018-02-19
        相关资源
        最近更新 更多