簡體   English   中英

不確定如何排序此JSON對象jQuery / JavaScript

[英]Not sure how to sort this JSON Object jQuery/JavaScript

樣本字符串:

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。 但是我想不出最好的方法。 有沒有一種方法可以使功能通過選擇來執行,或者我需要根據我想做的功能來創建一組功能,如果可以的話? 我上面的東西對我來說不起作用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM