2012-04-19 64 views
7

如何可以總結JSON數組這樣的元件時,使用jQuery:如何總結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",}], 

結果應該是:

totalTaxes = 60

+5

10?真? 25 + 25 + 10 = 10?你的JOSN無效。 – epascarello 2012-04-19 03:59:29

+0

幾個無與倫比的'{單曲 – kev 2012-04-19 04:01:06

+1

@epascarello:顯然,你有沒有聽說過「新數學」 – sberry 2012-04-19 04:02:03

回答

14

與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

除了這不是JSON。 [JSON](http://en.wikipedia.org/wiki/JSON)是一種文本格式。這只是javascript對象和數組表示法。 – jfriend00 2012-04-19 04:07:16

+0

謝謝。我採取了長JSON響應的一部分。我很抱歉在我的問題中的錯誤。但總數正在與此合作。 ;) – Louis 2012-04-19 04:42:03

10

如果你真的必須使用jQu ERY,你可以這樣做:

var totalTaxes = 0; 

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

或者你可以使用ES5 reduce功能,支持它的瀏覽器:

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

或者乾脆@ epascarello的答案使用for循環像...