首页 > 解决方案 > 如何按日期对列表进行分组

问题描述

我正在尝试使用下面的代码按日期显示列表,但出现异常无法获取未定义或空引用的属性“forEach”,有人可以帮助我,我在哪里做错了

home.ts:

this.events = [{
  id: 1,
  category:'camera',
  title: 'First event',
  date: '2017-12-26'
}, {
  id: 2,
  category:'accessories',
  title: 'Second event',
  date: '2017-12-27'
}, {
  id: 3,
  category:'camera',
  title: 'Third event',
  date: '2017-12-26'
}, {
  id: 4,
  category:'accessories',
  title: 'Fouth event',
  date: '2017-12-27'
},{
  id: 5,
  category:'camera',
  title: 'Fifth event',
  date: '2017-12-26'
}]

}

主页.html:

<ion-content padding>

    <ion-item-group *ngFor="let group of events | groupBy: 'date'">
        <ion-item-divider color="light">
            {{ group.date }}
        </ion-item-divider>
        <ion-item *ngFor="let event of group.events">{{ event.title }}</ion-item>
    </ion-item-group>

</ion-content>

分组日期:

@Pipe({name: 'groupByDate'})
export class GroupByPipeProvider implements PipeTransform {
    transform(collection: Array<any>, property: string = 'date'): Array<any> {
        if(!collection) {
            return null;
        }
        const gc = collection.reduce((previous, current)=> {
            if(!previous[current[property]]) {
                previous[current[property]] = [];
            }
                current.events.forEach(x => previous[current[property]].push(x));
            return previous;
        }, {});
        return Object.keys(gc).map(date => ({ date: date, events: gc[date] }));
        }  
}

标签: angularionic-frameworkionic3

解决方案


您必须为此创建一个自定义管道,就像我在这里所做的那样:

@Pipe({name: 'groupByDate'})
export class GroupByPipe implements PipeTransform {
transform(collection: Array<any>, property: string = 'date'): Array<any> {
    if(!collection) {
        return null;
    }
    const gc = collection.reduce((previous, current)=> {
        if(!previous[current[property]]) {
            previous[current[property]] = [];
        }
            current.events.forEach(x => previous[current[property]].push(x));
        return previous;
    }, {});
    return Object.keys(gc).map(date => ({ date: date, events: gc[date] }));
    }  
}

HTML:

<ul>
    <li *ngFor="let group of events | groupByDate">{{group.date}}
        <ul>
            <li *ngFor="let event of group.events">
            {{event.id}} {{event.title}}
            </li>
        </ul>
    </li>
</ul>

我在这里实现了解决方案:https ://stackblitz.com/edit/angular-ldhmnk

希望能帮助到你。


推荐阅读