2012-04-19 74 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循环像...