Javascript 如何对json数组求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10221455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:23:13  来源:igfitidea点击:

How to sum json array

javascriptjqueryjson

提问by Louis

How can I to sum elements of a JSON array like this, using jQuery:

如何使用 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",}],

The result should be:

结果应该是:

totalTaxes = 60

totalTaxes = 60

回答by epascarello

Working with JSON 101

使用 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

回答by Ates Goral

If you really mustuse jQuery, you can do this:

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

var totalTaxes = 0;

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

Or you can use the ES5 reducefunction, in browsers that support it:

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

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

Or simply use a for loop like in @epascarello's answer...

或者简单地使用像@epascarello's answer中的for循环......