我需要按日期排序这个json。我尝试使用此代码,但无法正常工作。 我的json
{
"StatusCode":0,
"StatusMessage":"OK",
"StatusDescription":[
{
"id":"1",
"datetime_device":"2018-03-13T23:00:00.000Z",
"alarmtype_id":1,
"alarmnumber":4,
"device_serial":"11"
},
{
"id":"2",
"datetime_device":"2018-03-20T23:00:00.000Z",
"alarmtype_id":2,
"alarmnumber":5,
"device_serial":"22"
},
{
"id":"3",
"datetime_device":"2018-03-12T23:00:00.000Z",
"alarmtype_id":2,
"alarmnumber":5,
"device_serial":"33"
},
{
"id":"4",
"datetime_device":"2018-03-19T23:00:00.000Z",
"alarmtype_id":1,
"alarmnumber":4,
"device_serial":"44"
}
]
}
我的代码:
public dueDate: Date;
public notif: Notifications[];
getAllNotifications() {
this.ws.NotifGetAll().subscribe(
notif=> {
this.notif= notif; // show me all value in json
}
);
}
private getTime(date?: Date) {
return date != null ? date.getTime() : 0;
}
public sortbydate(): void {
this.notif.sort(() => {
console.log(this.getTime(this.dueDate) - this.getTime(this.dueDate))
return this.getTime(this.dueDate) - this.getTime(this.dueDate);
});
}
我的服务:
public NotifGetAll(): Observable<Notifications[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.NotifGetAll), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(notif => {
return new Notifications(notif);
});
}
});
}
和通知类:
export class Notifications {
datetime_device: Date;
alarmtype_id: string;
device_serial: string;
id: string;
alarmnumber: number;
}
我的HTML代码: 单击此按钮时,在控制台中仅显示0
<div>
<p>Sort:</p>
<button (click)="sortbydate()">sort by date
</button>
</div>
结果是:没有正确排序并且在控制台中只显示0。
你能告诉我任何解决方案吗?
Thnx
答案 0 :(得分:0)
返回0,因为您在sortByDate()
函数中减去了相同的值。
您按this.dueDate
减去this.dueDate
:请参阅下面的代码。
return this.getTime(this.dueDate) - this.getTime(this.dueDate);
.sort()
函数返回一个已排序的数组,但您可以方便地使用函数表达式来实现目标。
public sortbydate(): void {
this.notif = this.notif.sort((date1, date2) =>
return this.getTime(date1.datetime_device) - this.getTime(date2.datetime_device)
);
}
答案 1 :(得分:0)
这不是排序功能的工作原理。您需要为sort
所比较的项声明参数并使用它们,并按以下方式使用:
this.notif.sort((a, b) => {
const sort = this.getTime(a.dueDate) - this.getTime(b.dueDate)
console.log(sort)
return sort;
});
(dueDate
可能不是正确的属性,它必须存在于您排序的项目上。也许您想在JSON中使用datetime_device
?)
答案 2 :(得分:0)
您正在减去相同的this.dueDate
值,并且您无法检索排序结果。试试这个:
public sortbydate(): void {
this.notif = this.notif.sort((a, b) =>
this.getTime(a.datetime_device) - this.getTime(b.datetime_device)
);
}