首页 > 解决方案 > RxJS Group By and and 获取远程数据的总和

问题描述

我有这样的远程 Web api 数据:

[
    {
        "courseName": "Matematik",
        "contentsCount": 2,
        "createdDate": "2019/10/20"
    },
    {
        "courseName": "Matematik",
        "contentsCount": 1,
        "createdDate": "2019/10/16"
    },
    {
        "courseName": "Matematik",
        "contentsCount": 1,
        "createdDate": "2019/10/17"
    },
    {
        "courseName": "Matematik",
        "contentsCount": 2,
        "createdDate": "2019/10/22"
    },
    {
        "courseName": "Matematik",
        "contentsCount": 1,
        "createdDate": "2019/08/21"
    },
    {
        "courseName": "Türkçe",
        "contentsCount": 1,
        "createdDate": "2019/10/20"
    },
    {
        "courseName": "Türkçe",
        "contentsCount": 1,
        "createdDate": "2019/10/18"
    },
    {
        "courseName": "Türkçe",
        "contentsCount": 1,
        "createdDate": "2019/10/21"
    },
    {
        "courseName": "Türkçe",
        "contentsCount": 1,
        "createdDate": "2019/08/22"
    },
    {
        "courseName": "Türkçe",
        "contentsCount": 1,
        "createdDate": "2019/09/21"
    },
    {
        "courseName": "Türkçe",
        "contentsCount": 1,
        "createdDate": "2019/09/22"
    }
]

我想在远程获取数据后对这些数据进行分组createdDate并求和。contentsCount

我正在使用 Angular 8 获取这样的数据。

return this.repository.getData(`api/course/contents/report/${this.teacherId}`)
      .pipe(
        groupBy(x => x["createdDate"]),
      )
       .toPromise()
       .catch(error => { throw 'Data Loading Error' });

那么我怎样才能在 RxJS 管道中做到这一点。

谢谢。

标签: angularrxjs

解决方案


你可以这样尝试:

  constructor() {
     var groupedData = this.groupByKey(this.data, "createdDate");

    Object.keys(groupedData).forEach(x => {
      this.res.push(
        {
          createdDate : x,
          contentsCount : (groupedData[x].map(y => y.contentsCount)).reduce(function(a, b) { return a + b; }, 0)
        }
      )
    });
  }

  groupByKey(data, key) {
    return data.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }

工作演示


推荐阅读