- const Employers=[
{employerName:"A1",employees:[{employeeName:"EA1"},{employeeName:"EA2"}]},
{employerName:"B1",employees:[{employeeName:"EB1"},{employeeName:"EB2"}]}
]
我的问题如何按employeeName对雇主进行排序。
答案 0 :(得分:1)
首先从已排序的员工中排序
_.sortBy(Employers, function(emp) {
return _.chain(emp)
.get('employees')
.sortBy('employeeName')
.map('employeeName')
.first()
.value();
});
答案 1 :(得分:0)
如果你可以改变数据结构,我建议你这样做:
const EmployersSortable = [
{ employerName: 'A1', employeeName: 'EA1' },
{ employerName: 'B1', employeeName: 'EB2' },
{ employerName: 'A1', employeeName: 'EA2' },
{ employerName: 'B1', employeeName: 'EB1' }
]
然后你可以这样做:EmployersSortable = _.sortBy(EmployersSortable, 'employeeName');
如果您无法更改数据结构,那么您将不得不迭代原始数据并通过执行以下操作将其转换为上述数据结构:
var EmployersSortable = [];
Employers.forEach(function(employerObj) {
employerObj.employees.forEach(function(employeeObj) {
EmployersSortable.push({
employerName: employerObj.employerName,
employeeName: employeeObj.employeeName
});
})
});