【问题标题】:D3.js hierarchy calculated summary by fieldD3.js 层次结构按字段计算汇总
【发布时间】:2021-05-23 10:13:11
【问题描述】:

请给我这样的扁平 json:

var data = [{ "Id": 1, "Name": "a1", "Parent": null},
           { "Id": 2, "Name": "a2", "Parent": 1},
           { "Id": 3, "Name": "a3", "Parent": 2, "nb1": 30, "nb2": 40 },
           { "Id": 4, "Name": "a4", "Parent": 2, "nb1": 25, "nb2": 64 },
           { "Id": 5, "Name": "a5", "Parent": 1},
           { "Id": 6, "Name": "a6", "Parent": 5, "nb1": 2, "nb2": 6 },
           { "Id": 7, "Name": "a7", "Parent": 5, "nb1": 5, "nb2": 4 }];

使用 d3js,我想为所有父母构建包含每个字段(nb1 和 nb2)的总和的层次化 json

我正在使用:

var treeData = d3.stratify().
id(function (d) { return d.Id; })
.parentId(function (d) { returnd.Parent; })(data);
treeData.sum(d=> d.nb1)

但它返回带有总和的新字段(值)。 我需要的是 nb1 的总和,并保持相同的字段名称 nb1 和 nb2 的总和,并为父母保留相同的名称字段 nb2。

另外,自定义d3js层级的sum函数。 非常感谢

【问题讨论】:

    标签: d3.js sum hierarchy


    【解决方案1】:

    使用递归buildNode函数:

    const data = [
      { "Id": 1, "Name": "a1", "Parent": null},
      { "Id": 2, "Name": "a2", "Parent": 1},
      { "Id": 3, "Name": "a3", "Parent": 2, "nb1": 30, "nb2": 40 },
      { "Id": 4, "Name": "a4", "Parent": 2, "nb1": 25, "nb2": 64 },
      { "Id": 5, "Name": "a5", "Parent": 1},
      { "Id": 6, "Name": "a6", "Parent": 5, "nb1": 2, "nb2": 6 },
      { "Id": 7, "Name": "a7", "Parent": 5, "nb1": 5, "nb2": 4 }];
      
    const getValue = (node, children, attr) => 
      children.length > 0 ? 
        children.reduce((s, n) => s + n[attr], 0) : 
        node[attr];
    
    const buildNode = (node) => {
      const children = data
       .filter(n => n.Parent === node.Id)
       .map(n => buildNode(n));
      
      const nb1 = getValue(node, children, 'nb1');  
      const nb2 = getValue(node, children, 'nb2');  
      return {...node, children, nb1, nb2};
    }
      
    const root = buildNode(data.find(n => !n.Parent));  
    
    console.log('ROOT: ', root)

    【讨论】:

    • 非常感谢最好的朋友。我还使用了 d3.hierarchy 中集成的 eachAfter 方法来获得相同的结果。但你的解决方案很棒而且很完美。
    猜你喜欢
    • 2013-02-09
    • 2021-09-11
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多