Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the largest value from Json object with Javascript

This should be an easy one. I just cant figure it out.

How do I get the largest value from this piece of JSON with javascript.

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

The key and value I need is:

"two":35 

as it is the highest

thanks

like image 966
32423hjh32423 Avatar asked Apr 12 '10 09:04

32423hjh32423


2 Answers

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
    }
  }
}
like image 185
Jonny Buchanan Avatar answered Sep 18 '22 12:09

Jonny Buchanan


If you have underscore:

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

How this works:

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'
like image 36
musa Avatar answered Sep 18 '22 12:09

musa