不知道如何排序这个JSON对象jQuery/JavaScript

Not sure how to sort this JSON Object jQuery/JavaScript

本文关键字:JSON 对象 jQuery JavaScript 何排序 排序 不知道      更新时间:2023-09-26

示例字符串:

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,根据名称,根据当前状态类。但我想不出最好的办法。有没有办法让一个函数可以做任何选择,或者我需要做一组基于我想做的函数,如果有的话,怎么做?

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);