在JavaScript中按日期对包含对象升序和降序的嵌套数组进行排序
假设我们有一个JSON对象,其中包含这样的嵌套数组-
const arr = {"DATA": [
{
"BookingID": "9513",
"DutyStart": "2016-02-11 12:00:00"
},
{
"BookingID": "91157307",
"DutyStart": "2016-02-11 13:00:00"
},
{
"BookingID": "95117317",
"DutyStart": "2016-02-11 13:30:00"
},
{
"BookingID": "957266",
"DutyStart": "2016-02-12 19:15:00"
},
{
"BookingID": "74",
"DutyStart": "2016-02-11 12:21:00"
}
]
};
我们需要编写一个JavaScript函数来接收一个这样的对象,并根据'dutyStart'属性以升序或降序对嵌套数组进行排序。
示例
为此的代码将是-
const arr = {"DATA": [
{
"BookingID": "9513",
"DutyStart": "2016-02-11 12:00:00"
},
{
"BookingID": "91157307",
"DutyStart": "2016-02-11 13:00:00"
},
{
"BookingID": "95117317",
"DutyStart": "2016-02-11 13:30:00"
},
{
"BookingID": "957266",
"DutyStart": "2016-02-12 19:15:00"
},
{
"BookingID": "74",
"DutyStart": "2016-02-11 12:21:00"
}
]
};
const sortByDate = arr => {
const sorter = (a, b) => {
return new Date(a.DutyStart).getTime() - new Date(b.DutyStart).getTime();
};
arr["DATA"].sort(sorter);
return arr;
};
console.log(sortByDate(arr));
输出结果
控制台中的输出将是-
{DATA: [
{ BookingID: '9513', DutyStart: '2016-02-11 12:00:00' },
{ BookingID: '74', DutyStart: '2016-02-11 12:21:00' },
{ BookingID: '91157307', DutyStart: '2016-02-11 13:00:00' },
{ BookingID: '95117317', DutyStart: '2016-02-11 13:30:00' },
{ BookingID: '957266', DutyStart: '2016-02-12 19:15:00' }
]
}
以上是 在JavaScript中按日期对包含对象升序和降序的嵌套数组进行排序 的全部内容, 来源链接: utcz.com/z/345302.html