我使用jQuery解析员工的JSON文件,其中包含他们的姓名、部门、子部门和其他一些详细信息。
例如:
[
{
"LAST":"Betsy",
"FIRST":"Jackson",
"DEPT":"Customer Service",
"SUBDEPT":"Tech Support",
"JOINED":"02/94",
"TITLE":"Technical Customer Service Representative",
"RESIDENCE":"Someplace",
"HOBBIES":"Reading, Walking, Sleeping"
},
{
"LAST":"Sally",
"FIRST":"Smith",
"DEPT":"Customer Service",
"SUBDEPT":"Installation Customer Service Representative",
"JOINED":"01/04",
"TITLE":"Technical Customer Service Representative",
"RESIDENCE":"Someplace",
"HOBBIES":"Reading, Walking, Sleeping"
},
]
我正在尝试构建一个应用程序,用户可以在该应用程序中单击员工的姓名,并查看结果的刷新,其中显示该员工所在部门的每个员工,按子部门组织,并向下滚动到给定的员工。
我已经成功地生成了一个员工姓名列表,其中包含用于保存其部门和子部门的data-*属性。当单击员工名称时,我已经能够第二次解析JSON文件,返回该部门的所有员工,并构建一个网格,然后将整个匹配的员工对象推送到一个名为"results"的新数组中
注意:dept=jquery选择器传递的数据dept。。
$.each(data, function(i, employee) {
if (employee.DEPT == dept) {
var employeetext = '<span class="name">'
+ employee.FIRST+' '+ employee.LAST+'</span>',
employee.JOINED,
employee.TITLE,
employee.RESIDENCE,
'...',
employee.HOBBIES;
$('#employees').append('<div class="employee_block"><img src="" width="85" height="113">' + employeetext + '.</div>');
results.push(employee);
}
}) // end stepping through employees
然而,我需要根据数组中的新排序顺序构建网格,而不是现在使用的y字母顺序。我需要根据优先级按子部门划分结果,优先级不是按字母顺序排列的,而是我希望在单独的对象中定义的自定义顺序(这会是"关系数据库吗?")例如:
var subdeptorder = [
{
"DEPT": "Marketing",
"SUBDEPTS": ["Administration", "Purchasing", "Advertising", "PR"]
},
{
"DEPT": "Sales",
"SUBDEPTS": ["Administration", "Business Development"]
}
]
因此,我需要根据其中员工的部门(以及该部门的子部门顺序)对"结果"数组进行排序。
如何编写比较函数,根据在单独对象中建立的优先级对"结果"数组进行重新排序?
像这样格式化单独的对象:
var subdeptorder = {
"Marketing": ["Administration", "Purchasing", "Advertising", "PR"],
"Sales": ["Administration", "Business Development"]
};
然后你可以这样对数据进行排序:
var dept = …; // the chosen one
var results = $.grep(data, function(employee) {
return employee.DEPT = dept;
}),
order = subdeptorder[dept];
results.sort(function(a, b) {
// sort them by the indices of their SUBDEPTs in the order array
return $.inArray(a.SUBDEPT, order) - $.inArray(b.SUBDEPT, order);
});
$.each(results, function(i, employee) {
$('#employees').append('<div class="employee_block"><img src="" width="85" height="113">' + [
'<span class="name">'+employee.FIRST+' '+employee.LAST+'</span>',
employee.JOINED,
employee.TITLE,
employee.RESIDENCE,
'…',
employee.HOBBIES
].join(' ') + '.</div>');
});
请参阅对自定义订单进行排序以获得优化版本(不是每次都使用$.inArray
作为索引)。