首页 > 解决方案 > 如何使用具有特定日期格式的分组键作为分组键的管道分组

问题描述

我有一个数据列表:

  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];

我正在听取您的解决方案建议

标签: angulartypescript

解决方案


您可以在分组之前转换集合的日期:

  @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] }));
  }
}

推荐阅读