2012-04-19 157 views
7

¿Cómo puedo resumir los elementos de una matriz JSON como este, usando jQuery:Cómo sumar matriz JSON

"taxes": [ { "amount": 25, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI", 
{ "amount": 25, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI", 
{ "amount": 10, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI",}], 

El resultado debe ser:

totalTaxes = 60

+5

10? De Verdad? 25 + 25 + 10 = 10? Y tu JOSN no es válido. – epascarello

+0

varios '{' s – kev

+1

inigualable @epascarello: obviamente no has oído hablar de "nuevas matemáticas" – sberry

Respuesta

14

Trabajar con JSON 101

var foo = { 
     taxes: [ 
      { amount: 25, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"}, 
      { amount: 25, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"}, 
      { amount: 10, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"} 
     ] 
    }, 
    total = 0, //set a variable that holds our total 
    taxes = foo.taxes, //reference the element in the "JSON" aka object literal we want 
    i; 
for (i = 0; i < taxes.length; i++) { //loop through the array 
    total += taxes[i].amount; //Do the math! 
} 
console.log(total); //display the result 
+4

Excepto que esto no es JSON. [JSON] (http://en.wikipedia.org/wiki/JSON) es un formato de texto. Esto es solo un objeto javascript y una notación de matriz. – jfriend00

+0

Gracias. Tomé parte de una larga respuesta JSON. Lo siento los errores en mi pregunta. Pero la suma está trabajando con esto. ;) – Louis

10

Si usted realmente debe utilice jQu ery, usted puede hacer esto:

var totalTaxes = 0; 

$.each(taxes, function() { 
    totalTaxes += this.amount; 
}); 

O puede utilizar la función ES5 reduce, en los navegadores que lo soportan:

totalTaxes = taxes.reduce(function (sum, tax) { 
    return sum + tax.amount; 
}, 0); 

O simplemente utilizar un bucle como en la respuesta de @ epascarello ...