本文介绍了如何按日期对列表进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码按日期显示列表但我得到异常无法获取属性'forEach'未定义或空引用可以是一个请帮帮我,我在哪里做错误包装
I am trying to show list with group by date using below code but i am getting exceptions Unable to get property 'forEach' of undefined or null reference can some one help me please where did i do mistack
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'
}]
}
<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>
GroupByDate:
GroupByDate:
@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] }));
}
}
推荐答案
你必须为此创建一个自定义管道,就像我在这里所做的那样:
You have to create a custom Pipe for this just like I have done here:
@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>
我在这里实施了解决方案:
I have implemented the solution here: https://stackblitz.com/edit/angular-ldhmnk
希望有所帮助。
这篇关于如何按日期对列表进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!