如何通过jQuery或javascript在json格式的数据中为父母计算孩子的递归总和

时间:2019-06-10 15:35:09

标签: javascript jquery

我想知道如何通过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
    }]
}

1 个答案:

答案 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];
}