【问题标题】:Get the largest value from Json object with Javascript使用Javascript从Json对象中获取最大值
【发布时间】:2011-02-06 22:25:10
【问题描述】:

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

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

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

我需要的key和value是:

"two":35 

因为它是最高的

谢谢

【问题讨论】:

    标签: javascript json sorting


    【解决方案1】:
    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
        }
      }
    }
    

    【讨论】:

    • @Insin hasOwnProperty 是什么意思?你为什么用eval?
    • @systempuntoout hasOwnProperty 防止顽皮的库向 Object.prototype 添加内容,因为我们不知道执行此代码的完整上下文。我使用 eval() 作为关于 JSON 的问题 - JSON 是一种文本格式,因此始终采用符合 json.org 规范的字符串形式。可能是提问者将 JSON 与 Object Literal Notation 混淆了(有很多很多误导性的教程/文章对此无济于事),这就是我为什么要使用 JSON 文本的原因。跨度>
    • @insin 如何在 android 中做同样的事情?
    【解决方案2】:

    如果你有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'
    

    【讨论】:

      【解决方案3】:

      这是我的最大键功能

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

      【讨论】:

      • +1 是唯一正确处理负值的解决方案。
      【解决方案4】:

      你也可以在解析 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多