Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript从Json对象获取最大值_Javascript_Json_Sorting - Fatal编程技术网

使用Javascript从Json对象获取最大值

使用Javascript从Json对象获取最大值,javascript,json,sorting,Javascript,Json,Sorting,这应该很容易。我就是想不出来 如何使用javascript从这段JSON中获得最大值 {"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}} 我需要的关键和价值是: "two":35 因为它是最高的 谢谢这是我的最大键功能 function maxKey(a) { var max, k; // don't set max=0, becau

这应该很容易。我就是想不出来

如何使用javascript从这段JSON中获得最大值

{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}
我需要的关键和价值是:

"two":35 
因为它是最高的


谢谢

这是我的最大键功能

function maxKey(a) {  
  var max, k; // don't set max=0, because keys may have values < 0  
  for (var key in a) { if (a.hasOwnProperty(key)) { max = parseInt(key); break; }} //get any key  
  for (var key in a) { if (a.hasOwnProperty(key)) { if((k = parseInt(key)) > max) max = k; }}  
  return max;  
} 
函数maxKey(a){
var max,k;//不要设置max=0,因为键的值可能小于0
对于(a中的var key){if(a.hasOwnProperty(key)){max=parseInt(key);break;}}//获取任意键
对于(a中的var key){if(a.hasOwnProperty(key)){if((k=parseInt(key))>max)max=k;}
返回最大值;
} 
如果您有:

工作原理:

var data = {one:21, two:35, three:24, four:2, five:18};
var inverted = _.invert(data); // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'};
var max = _.max(data); // 35
var max_key = inverted[max]; // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'}[35] => 'two'

还可以在解析JSON后迭代对象

var arr = jQuery.parseJSON('{"one":21,"two":35,"three":24,"four":2,"five":18}' );

var maxValue = 0;

for (key in arr)
{
     if (arr[key] > maxValue)
     {
          maxValue = arr[key];   
     }
}

console.log(maxValue);

@Insin hasOwnProperty是什么意思?为什么使用eval?@SystemPuntoot hasOwnProperty防止顽皮的库向Object.prototype添加内容,因为我们不知道执行此代码的完整上下文。我使用eval()来回答关于JSON的问题——JSON是一种文本格式,因此总是采用符合JSON.org规范的字符串形式。可能是提问者把JSON和对象文字符号混淆了(有很多很多误导性的教程/文章都没有帮助),这就是我为什么要使用JSON文本的原因。@insin如何在android中做同样的事情?+1是唯一正确处理负值的解决方案。
var data = {one:21, two:35, three:24, four:2, five:18};
var inverted = _.invert(data); // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'};
var max = _.max(data); // 35
var max_key = inverted[max]; // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'}[35] => 'two'
var arr = jQuery.parseJSON('{"one":21,"two":35,"three":24,"four":2,"five":18}' );

var maxValue = 0;

for (key in arr)
{
     if (arr[key] > maxValue)
     {
          maxValue = arr[key];   
     }
}

console.log(maxValue);