Javascript 聚合json数据中的值
如何对json数据集中的值求和? 我正在尝试对数据集中字段Javascript 聚合json数据中的值,javascript,json,xmlhttprequest,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
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();
下面是数据的快照
:
如果我们检查上面返回的数组中的其中一项:
{
[functions]: ,
__proto__: { },
AccountID: null,
AccountUID: null,
AgentCost: 0,
Amount: 24.3,
AccountsItemID: null,
TaxAmount: 2.01
}
我已尝试对所有元素进行求和,例如:
var totalTaxAmount = data.reduce(function(pv, cv) {
pv += cv["TaxAmount"];
}, {});
也许我需要做一个data.forEach.reduce
如何对json数据集中的值求和?请尝试以下操作:
var-arr=[
{
AccountID:null,
AccountUID:null,
代理成本:0,
金额:24.3,
AccountsItemID:null,
税额:2.01
},
{
AccountID:null,
AccountUID:null,
代理成本:0,
金额:24.3,
AccountsItemID:null,
税额:3.01
}
];
var totalTaxAmount=arr.reduce(函数(pv,cv){
pv+=cv[“税额”];
返回pv;
}, 0);
console.log(totalTaxAmount)代码>如注释所示;您需要返回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
);
您需要从传递到reduce
的函数返回pv
。为什么我们每次都返回pv,而不是只返回一次?为什么我们每次都返回pv,我们需要返回,而不是只返回一次,因为每次迭代后,我们都会将当前值添加到累加器中。这个返回值将成为我们的新累加器。