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)
如果你有下划线:
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)