Alex Gordon
Alex Gordon

Reputation: 60811

aggregating values within json data

How do I sum values in a json data set?

I'm trying to sum all values in my dataset for the field TaxAmount:

var url = "https://...........";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        var data = JSON.parse(xhr.response);
        console.log(data);           

    }
};
xhr.open("GET", url, true);
xhr.send();

here's a snapshot of data:

enter image description here

If we inspect one of these items in the array returned above:

{
   [functions]: ,
   __proto__: { },
   AccountID: null,
   AccountUID: null,
   AgentCost: 0,
   Amount: 24.3,
   AccountsItemID: null,
   TaxAmount: 2.01
}

I've attempted to sum TaxAmount for all elements like so:

    var totalTaxAmount = data.reduce(function(pv, cv) {             
         pv += cv["TaxAmount"];
    }, {});

Perhaps I need to do a data.forEach.reduce?

How do I sum values in a json data set?

Upvotes: 1

Views: 37

Answers (2)

HMR
HMR

Reputation: 39290

As commented; you need to return sum of pv and cv and you need the second argument to reduce to be 0 instead of an object:

var totalTaxAmount = data.reduce(
  function(pv, cv) {
    /** added return and no need to change pv */return pv + cv["TaxAmount"];
  }, 
  /** changed to zero */0
);

Upvotes: 1

amrender singh
amrender singh

Reputation: 8239

Try the following:

var arr = [
{
   AccountID: null,
   AccountUID: null,
   AgentCost: 0,
   Amount: 24.3,
   AccountsItemID: null,
   TaxAmount: 2.01
},
{
   AccountID: null,
   AccountUID: null,
   AgentCost: 0,
   Amount: 24.3,
   AccountsItemID: null,
   TaxAmount: 3.01
}
];

 var totalTaxAmount = arr.reduce(function(pv, cv) {             
         pv += cv["TaxAmount"];
         return pv;
    }, 0);
console.log(totalTaxAmount);

Upvotes: 2

Related Questions