这是我正在使用的对象的一个简短示例。
{
"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/