不确定如何对JSON对象jQuery/JavaScript进行排序 [英] Not sure how to sort this JSON Object jQuery/JavaScript

查看:112
本文介绍了不确定如何对JSON对象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"}
]};

我的饼干杰克尝试这样做.

My Cracker Jack Attempt at doing it.

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.但是我不知道最好的方法.有没有一种方法可以使功能通过选择来执行,或者我需要根据我想做的功能来创建一组功能,如果可以的话?我上面的东西对我不起作用.

I actually need to figure out how to sort this various ways. Such as by hostidn, by name, by currstatusclass. But I can't figure out the best way to do it. Is there a way to make a function that could do any by choice or would I need to make a set of functions based on which i want to do, if either how? mine above is not working out for me.

推荐答案

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

这篇关于不确定如何对JSON对象jQuery/JavaScript进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆