我想知道如何通过jQuery或javascript在json格式的数据中为父母计算孩子的递归总和。 假设我有一个json格式的数据,如下所示:
{
"data": [{
"ID": "1",
"AccountName": "a",
"ParentID": "",
"OpeningDebit": 0,
"OpeningCredit": 0
}, {
"ID": "2",
"AccountName": "b",
"ParentID": "1",
"OpeningDebit": 0,
"OpeningCredit": 0
}, {
"ID": "3",
"AccountName": "c",
"ParentID": "2",
"OpeningDebit": 100,
"OpeningCredit": 200
}]
}
我想通过像这样的递归jQuery或javascript函数计算其父项的所有子项总和:
{
"data": [{
"ID": "1",
"AccountName": "a",
"ParentID": "",
"OpeningDebit": 100,
"OpeningCredit": 200
}, {
"ID": "2",
"AccountName": "b",
"ParentID": "1",
"OpeningDebit": 100,
"OpeningCredit": 200
}, {
"ID": "3",
"AccountName": "c",
"ParentID": "2",
"OpeningDebit": 100,
"OpeningCredit": 200
}]
}
答案 0 :(得分:0)
尝试递归减少:
function recurseSum(element, key) {
const children = data.filter(child => child.parentID === element.ID);
if (children.length <= 0) {
element['sum' + key] = element[key];
return element[key];
}
element['sum' + key] = element[key] + chidlren.reduce((sum, child) => {
return sum + recurseSum(child, key);
}, 0);
return element['sum' + key];
}