angular - 如何使用具有特定日期格式的分组键作为分组键的管道分组
问题描述
我有一个数据列表:
players = [{name: 'Gene', team: 'team alpha', date: '2019-09-18T16:45:42' },
{name: 'Steve', team: 'team gamma', date: '2019-09-18T15:45:42'},
{name: 'George', team: 'team beta', date: '2019-20-18T12:45:42'},
{name: 'Paula', team: 'team beta', date: '2019-18-18T15:45:42'},
{name: 'Jhon', team: 'team gamma', date: '2019-09-18T15:45:42'}];
}
我想使用仅在日期上而不是格式“2019-09-18T15:45:42”的分组管道,它应该只在以下格式“2019-09-18”上完成,这更多与组一致。
这是使用的管道:
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(collection: Array<any>, property: string): Array<any> {
if(!collection) {
return null;
}
const groupedCollection = collection.reduce((previous, current)=> {
if(!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
和 html :
<ul>
<div *ngFor="let player of players | groupBy:'date'"> Team : {{player.key}}
<li *ngFor="let eachplayer of player.value">
{{eachplayer.name}}
</li>
</div>
</ul>
https://stackblitz.com/edit/angular-h2ve9k?file=src/app/app.component.html
我认为像这样重新处理日期会很方便,但我不知道在哪里可以使用它
date.split('T')[0];
我正在听取您的解决方案建议
解决方案
您可以在分组之前转换集合的日期:
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(collection: Array<any>, property: string): Array<any> {
if(!collection) {
return null;
}
const mappedCollection = collection.map(player => ({
...player,
date: player.date.split('T')[0]
}));
const groupedCollection = mappedCollection.reduce((previous, current)=> {
if(!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
推荐阅读
- adobe - AEM 6.5.6 + 静态模板:如何在内置页面属性的现有字段集中添加其他字段?
- firebase - 如果路径不以斜杠 (/) 开头,Firebase 存储删除然后创建对象到路径
- html - Bootstrap 4 未正确居中
- postgresql - Postgresql 没有运行
- javascript - React 如何使用 refs 来聚焦/模糊?
- python - python - 如何根据python中训练集的均值和标准来扩展测试集?
- r - 为什么在 R 中使用栅格包的地形函数时坡度值会变得如此之高?
- node.js - 为什么我在 Nodejs 中收到“无法在将标头发送到客户端后设置标头”错误?
- python - 如何在python中模拟一个rest API
- jestjs - 如何让 Jest 在 node_modules 中查看?