[英]Sorting an Array of JSON objects by date - Angular2
I am trying to sort an array of objects in Angular2. 我正在尝试对Angular2中的对象数组进行排序。 The best way to explain is to give code examples:
最好的解释方法是给出代码示例:
var activity = { SEQ_NO: -1, SIGNUP_NAME: "Testing Activity", SHORT_DESCRIPTION: "This activity min: 2, max: 25", EVENT_BEGIN_DATE: "2018/09/25", EVENT_END_DATE: "2018/09/25" };
The array is filled with objects like seen above. 数组中填充了如上所示的对象。 My goal is to take the array and sort it based on the date.
我的目标是获取数组并根据日期对其进行排序。 I also call a convert date function that takes the numeric date and turns it to a readable format:
我还调用了转换日期函数,该函数接受数字日期并将其转换为可读格式:
convertDate(incomingDate) { var myDate = new Date(incomingDate); var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; console.log(days[myDate.getDay()]); var date = days[myDate.getDay()]+" "+(myDate.getMonth()+1)+'/'+myDate.getDate()+'/'+myDate.getFullYear(); //alert(date); return date; }
So the activity object shown in this example will convert to: Tuesday 9/25/2018
因此,此示例中显示的活动对象将转换为:
Tuesday 9/25/2018
How can I sort an array of these objects by date? 如何按日期对这些对象的数组排序? When I display them, I am wanting to display them in order of months.
当我显示它们时,我想按月显示它们。
Thanks everyone in advanced. 谢谢大家。
First I would convert your date to a unix time as those will already be sorted by month. 首先,我会将您的日期转换为Unix时间,因为这些日期已经按月份进行了排序。
Second I would simply just sort your array by that number . 其次,我只是按该数字对数组进行排序 。
Since you are using typescript. 由于您正在使用打字稿。
component.html component.html
<div *ngFor="let sorted of sortedArray$ | async">
{{sorted.start}}
</div>
component.ts component.ts
list: any[] = [{
start: '2018/09/25',
content: 'second'
},{
start: '2018/08/10',
content: 'first'
}];
sortedArray$: Observable<any[]>;
constructor(public navCtrl: NavController) {
this.sortedArray$ = Observable.of(this.list)
.map((data) => {
data.sort((a, b) => {
return new Date(a.start.getTime()) > new Date(b.start.getTime());
});
return data;
});
}
When a string date is in the format yyyy/mm/dd it can be properly sorted without converting. 当字符串日期的格式为yyyy / mm / dd时,可以正确排序而不进行转换。
list.sort(function (a, b) {
a = a.EVENT_BEGIN_DATE;
b = b.EVENT_BEGIN_DATE;
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
});
You can then convert the dates. 然后,您可以转换日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.