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

324*_*423 8 javascript sorting json

这应该很简单.我只是想不通.

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

{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}
Run Code Online (Sandbox Code Playgroud)

我需要的关键和价值是:

"two":35 
Run Code Online (Sandbox Code Playgroud)

因为它是最高的

谢谢

Jon*_*nan 10

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @systempuntoout hasOwnProperty防止顽皮库向Object.prototype添加内容,因为我们不知道执行此代码的完整上下文.我使用eval()作为关于JSON的问题 - JSON是一种文本格式,所以总是采用符合json.org规范的字符串形式.问题提示者可能会将JSON与Object Literal Notation混淆(有很多很多误导性的教程/文章都没有帮助),这就是我为什么要使用JSON文本. (3认同)
  • 请注意,这仅在最大属性大于-1时有效。 (2认同)

mus*_*usa 8

如果你有下划线:

var max_key = _.invert(data)[_.max(data)];
Run Code Online (Sandbox Code Playgroud)

这是如何工作的:

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'
Run Code Online (Sandbox Code Playgroud)