【问题标题】:aggregating values within json data在 json 数据中聚合值
【发布时间】:2018-06-04 23:20:33
【问题描述】:

如何对 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的快照:

如果我们检查上面返回的数组中的这些项目之一:

{
   [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 数据集中的值求和?

【问题讨论】:

  • 你需要从传递给reduce的函数中返回pv
  • 为什么我们每次都返回pv,而不是只返回ONCE?

标签: javascript json xmlhttprequest


【解决方案1】:

尝试以下方法:

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

【讨论】:

  • 为什么我们每次都返回pv,而不是只返回ONCE?
  • @l--''''''---------'''''''''''''''''''' 我们需要返回,因为在每次迭代之后我们会添加我们的累加器的当前值。这个返回值将成为我们的新累加器。
【解决方案2】:

如评论;您需要返回 pv 和 cv 的总和,并且您需要将第二个参数减少为 0 而不是对象:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2021-09-24
    • 2017-09-07
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多