Underscore.js - 如何对嵌套的对象数组进行排序

时间:2016-10-25 14:25:57

标签: javascript arrays sorting underscore.js

我有以下javascript对象:

var appointments = [];

appointments.push(
       { id: '101', 
         status: 'accepted',
         appointmentTimes: [ { from: '2016-10-28 12:00', to: '2016-10-28 13:00' } ] },

       { id: '102', 
         status: 'pending', 
         appointmentTimes: [ { from: '2016-10-24 12:00', to: '2016-10-24 13:00' },  
                             { from: '2016-10-24 15:00', to: '2016-10-24 16:00' } ] });

我想使用appointmentTimes属性使用from数组中的第一项对数组对象进行排序,以便每个对象按升序日期顺序显示。

因此,在上面的示例中,id为102的对象将首先出现在列表中。请注意,appointmentTimes数组中的每个项目都已按升序排列。

我尝试了以下但是它不起作用:

_.sortBy(appointments, function(appointments) { 
        return appointments.appointmentTimes.from; 
 });

1 个答案:

答案 0 :(得分:0)

管理修复:

_.sortBy(appointments, function(appointment) { 
    return appointment.appointmentTimes[0].from; 
});
相关问题