示例字符串:
var output = {
"myservices":[
{"name":"oozie", "hostidn": "1", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
{"name":"oozie", "hostidn": "2", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
{"name":"oozie", "hostidn": "3", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
{"name":"oozie", "hostidn": "4", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
{"name":"oozie", "hostidn": "5", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
{"name":"single-namenode", "hostidn": "2", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}
]};
我的饼干杰克试图这样做。
function sortJSONresultsByHost(a,b)
{
var objectIDA = parseInt(a.hostidn, 10)
var objectIDB = parseInt(b.hostidn, 10)
if(objectIDA === objectIDB)
{
return 0;
}
return objectIDA > objectIDB ? 1 : -1;
}
output.myservices.sort(sortJSONresultsByHost);
我实际上需要弄清楚如何以各种方式进行排序。例如由hostidn,名字,由currstatusclass。但我无法弄清楚最好的方法。有没有办法制作一个可以通过选择做任何事情的功能,或者我需要根据我想要做的一组功能,如果有的话?我的上面不适合我。
答案 0 :(得分:3)
function sortObjectsByKey(objects, key){
objects.sort(function() {
return function(a, b){
var objectIDA = a[key];
var objectIDB = b[key];
if (objectIDA === objectIDB) {
return 0;
}
return objectIDA > objectIDB ? 1 : -1;
};
}());
}
sortObjectsByKey(output.myservices, "hostidn");
console.log(output.myservices);