Is there a way to calculate the total sum of values in a JSON dataset?
I'm attempting to add up all the values in my dataset under the field TaxAmount
:
const url = "https://...........";
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
const data = JSON.parse(xhr.response);
console.log(data);
}
};
xhr.open("GET", url, true);
xhr.send();
Here is a peek at the data
:
https://i.sstatic.net/ZqXie.png
If we examine one of the objects in the array returned above:
{
[functions]: ,
__proto__: { },
AccountID: null,
AccountUID: null,
AgentCost: 0,
Amount: 24.3,
AccountsItemID: null,
TaxAmount: 2.01
}
I've made an effort to total the TaxAmount
for all elements as follows:
let totalTaxAmount = data.reduce(function(previousValue, currentValue) {
return previousValue += currentValue["TaxAmount"];
}, 0);
Do you think using a data.forEach.reduce
would be more appropriate?
Is there a way to calculate the total sum of values in a JSON dataset?