2010-04-12 20 views
8

Questo dovrebbe essere facile. Non riesco a capirlo.Ottieni il valore più grande dall'oggetto Json con Javascript

Come ottengo il valore più grande da questo pezzo di JSON con javascript.

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

La chiave e il valore che mi serve è:

"two":35 

in quanto è il più alto

grazie

risposta

9
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 
    } 
    } 
} 
+0

L'uso di hasOwnProperty() è un buon punto. –

+0

@Insin Che cosa significa hasOwnProperty? Perché hai usato eval? – systempuntoout

+2

@systempuntoout hasOwnProperty protegge da librerie cattive aggiungendo oggetti a Object.prototype, in quanto non conosciamo il contesto completo in cui verrà eseguito questo codice. Ho usato eval() come la domanda è stata posta riguardo a JSON - JSON è un formato di testo, quindi assume sempre la forma di stringhe conformi alla specifica di json.org. Potrebbe darsi che il richiedente domande abbia confuso JSON con Object Literal Notation (ci sono molti, troppi tutorial/articoli fuorvianti là fuori che non aiutano in questo), che io perché ho fatto un punto di usare un testo JSON. –

1

Questo è il mio funzione per la più grande chiave

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

+1 per essere l'unica soluzione che gestisce correttamente i valori negativi. –

8

Se hai underscore:

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

Come funziona:

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' 
0

È inoltre possibile scorrere l'oggetto dopo si analizza 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); 
Problemi correlati