11

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

4

2 に答える 2

27

JSON101の操作

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
于 2012-04-19T04:03:46.190 に答える
15

本当にjQueryを使用する必要がある場合は、次のように実行できます。

var totalTaxes = 0;

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

reduceまたは、ES5機能をサポートするブラウザでES5機能を使用できます。

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

または、@epascarelloの回答のようにforループを使用するだけです...

于 2012-04-19T04:05:33.637 に答える