如何总结json数组 [英] How to sum json array

查看:98
本文介绍了如何总结json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jQuery对这样的JSON数组元素求和:

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

"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

推荐答案

使用JSON 101

Working with 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

这篇关于如何总结json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆