2010-04-12 31 views
8

这应该是一个简单的方法。我只是不知道。使用Javascript从Json对象获取最大值

如何从javascript中获取这段JSON的最大值。

{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}} 

我需要的键和值是:

"two":35 

,因为它是最高

感谢

回答

9
var jsonText = '{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}' 
var data = JSON.parse(jsonText).data 
var maxProp = null 
var maxValue = -1 
for (var prop in data) { 
    if (data.hasOwnProperty(prop)) { 
    var value = data[prop] 
    if (value > maxValue) { 
     maxProp = prop 
     maxValue = value 
    } 
    } 
} 
+0

使用hasOwnProperty()是一个很好的观点。 – 2010-04-12 09:41:56

+0

@Insin hasOwnProperty是什么意思?为什么使用eval? – systempuntoout 2010-04-12 09:44:06

+2

@systempuntoout hasOwnProperty可以防止顽皮的库向Object.prototype添加东西,因为我们不知道将执行此代码的完整上下文。 我用eval()作为JSON的问题 - JSON是一种文本格式,因此总是采用符合json.org规范的字符串形式。这可能是问题提供者将JSON与对象文字符号混淆(有很多很多误导教程/文章,这些文章对此没有帮助),这是我为什么使用JSON文本的原因。 – 2010-04-12 10:35:30

1

这是我的功能最大的关键

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; 
} 
+0

+1是正确处理负值的唯一解决方案。 – 2013-08-15 02:41:27

8

如果你有underscore

var max_key = _.invert(data)[_.max(data)]; 

这是如何工作的:

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' 
0

你也可以遍历对象,你解析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);