如何总结json数组

Lou*_*uis 9 javascript jquery 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",}],
Run Code Online (Sandbox Code Playgroud)

结果应该是:

totalTaxes = 60

epa*_*llo 22

使用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
Run Code Online (Sandbox Code Playgroud)

  • 除了这不是JSON.[JSON](http://en.wikipedia.org/wiki/JSON)是一种文本格式.这只是javascript对象和数组表示法. (4认同)

Ate*_*ral 13

如果你真的必须使用jQuery,你可以这样做:

var totalTaxes = 0;

$.each(taxes, function () {
    totalTaxes += this.amount;
});
Run Code Online (Sandbox Code Playgroud)

或者您可以reduce在支持它的浏览器中使用ES5 功能:

totalTaxes = taxes.reduce(function (sum, tax) {
    return sum + tax.amount;
}, 0);
Run Code Online (Sandbox Code Playgroud)

或者简单地使用@ epascarello的答案中的for循环......