11

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" }
]

The result should be:

totalTaxes = 60

8
  • 6
    10? Really? 25 + 25 + 10 = 10? And your JOSN is not valid. Commented Apr 19, 2012 at 3:59
  • 1
    @epascarello: obviously you haven't heard of "new math" Commented Apr 19, 2012 at 4:02
  • @Louis: You forgot the minus sign in front of one of those 25's. Commented Apr 19, 2012 at 4:02
  • 2
    @epascarello The result is in base-60. Commented Apr 19, 2012 at 4:03
  • What is wrong with looping on taxes[i].amount? Commented Apr 19, 2012 at 4:06

2 Answers 2

27

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
Sign up to request clarification or add additional context in comments.

2 Comments

Except this isn't JSON. JSON is a text format. This is just javascript object and array notation.
Thank you. I took a part of a long JSON response. I'm sorry the mistakes in my question. But the sum is working with this. ;)
15

If you really must use jQuery, you can do this:

var totalTaxes = 0;

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

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.