angular - 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 管道中做到这一点。
谢谢。
解决方案
你可以这样尝试:
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;
}, {});
}
推荐阅读
- typescript - 打字稿泛型:这里有什么问题?
- list - R 函数创建:嵌套循环“`*tmp*`[[i]] 中的错误:下标越界”
- android - 未安装本机 armeabi 库,但它们位于 APK 中
- python - Pygame 安装在 Windows 上,尝试调用 pygame.image.load() 时出现“pygame.error: Failed loading libwebp-7.dll”
- html - 使整个表格行可拖动但只能单击该行中的一个按钮开始拖动
- c++ - 抑制来自外部库的 UndefinedBehaviorSanitizer 警告
- javascript - 如何放置唯一的弹性项目,就好像有下一个一样?
- angular - html2canvas 不返回谷歌地图标记角
- r - R:如何选择列的子集并在多列上重复此操作
- typescript - 打字稿在函数类型声明中预期'=>'