假设我们有一个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' } ] }