views:

89

answers:

2

Hi

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

+3  A: 
var foo = {"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}};

var largest = {
    key: null,
    val: null
};

for(var i in foo.data){
    if( foo.data[i]>largest.val ){
        largest.key = i;
        largest.val = foo.data[i];
    }
}
alert(largest.key + "\n" + largest.val);
Álvaro G. Vicario
+3  A: 
var json = '{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}';
var obj = eval("(" + json + ")");
var maxKey;
var maxValue = 0;
for (key in obj.data)
{
    if (obj.data.hasOwnProperty(key))
    {
        var value = parseInt(obj.data[key], 10);
        if (value > maxValue)
        {
            maxKey = key;
            maxValue = value;
        }
    }
}
insin
Using hasOwnProperty() is a good point.
Álvaro G. Vicario
@Insin What does hasOwnProperty mean?Why you used eval?
systempuntoout
@systempuntoout hasOwnProperty guards against naughty libraries adding things to Object.prototype, as we don't know the full context in which this code will be executed.I used eval() as the question was asked with regard to JSON - JSON is a text format, so always takes the form of strings which conform to the specification at json.org. It could be that the question asker was confusing JSON with Object Literal Notation (there are many, many misleading tutorials/articles out there which don't help with that), which I why I made a point of using a JSON text.
insin
@insin +1 for the clear explanation!
systempuntoout