javascript - 如何使用 JavaScript 或 jQuery 在多维 JSON 对象中找到特定节点的最大值

标签 javascript jquery json sorting object

这是我正在使用的对象的一个​​简短示例。

{
    "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"
        }
    ]
}

在遍历所有这些并显示它们之前,我最终想找到最高的“hostidn”是什么。 hostidn 是第 N 个数字,它可以是唯一的数字,也可以是数百深,中间有几个重复的数字。我的目标是找到最高的那个,并根据它做一个 for 或 while 循环,将它们组合在一起进行视觉显示。示例注意,我在下面有一个编号为 2 的 hostidn,而其余的都有自己的。我想将两者与 2 一起放在一个框中进行显示,但在这种情况下有 5 个不同的 hostidn。我不知道,也许我想错了,不过我会采纳建议。

最佳答案

你可以遵循的基本算法

像这样声明一个变量并将其设置为零

$currentHighest=0;

然后遍历 json 数组并在每次迭代中将 hostidn 的值与 $currentHighest 比较,如果该值高于 中已经存在的值>$currentHighest 将该值设置为 $currentHighest

$currentHighest=0;
 $(data.myservices).each(function(index, element){
   if(data.myservices[index].hostidn>$currentHighest)
     $currentHighest=data.myservices[index].hostidn;
  });
//loop ends and `$currentHighest` will have the highest value

在迭代结束时,您将获得 $currentHighest

中的最高值

久经考验

$(function(){
 $.post("highest.json",function(data){
 $currentHighest=0;
  $(data.myservices).each(function(index, element){
   if(data.myservices[index].hostidn>$currentHighest)
     $currentHighest=data.myservices[index].hostidn;
  });
alert($currentHighest);
},'json');
});

关于javascript - 如何使用 JavaScript 或 jQuery 在多维 JSON 对象中找到特定节点的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7718701/

相关文章:

javascript - 提交事件未触发

c# - 在 C# 中解析尴尬的 JSON 格式

javascript - 淡出效果完成后如何运行.remove()?

javascript - 是否可以从 C#(或 C++)获取 HTML 元素(如 iFrame、div 等)的窗口句柄?

javascript - 使用angularjs隐藏表列的最有效方法

javascript - 如何在jquery中隐藏数据过滤器?

javascript - 检查一个 div 而不是一个复选框

javascript - 如何使用 kinetic jquery 方法旋转 Canvas 中的文本

arrays - Polymer 1.0 将 JSON 字符串作为属性传递

php - 如何操作/访问从自动完成 ajax 收到的 json?