聚合json数据中的值

时间:2018-06-04 15:10:32

标签: javascript json xmlhttprequest

如何对json数据集中的值求和?

我尝试对字段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();

这里是data的快照:

enter image description here

如果我们检查上面返回的数组中的其中一个项目:

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

我试图对所有元素求TaxAmount如下:

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

也许我需要做一个data.forEach.reduce

如何对json数据集中的值求和?

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

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);

答案 1 :(得分:1)

评论;你需要返回pv和cv的总和,你需要第二个参数reduce减为0而不是一个对象:

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