jamal
jamal

Reputation: 229

D3.js hierarchy calculated summary by field

Please I have flat json like this :

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

using d3js, I want to builde hierarchcal json with sum of each fields (nb1 and nb2) for all parents

I am using :

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

But it return new field (value) with sum. What I need is sum of nb1 and keep the same field name nb1 and sum of nb2 and keep the same name field nb2 for parents.

In other way, customize the sum function of d3js hierarchy. Thanks lot

Upvotes: 0

Views: 227

Answers (1)

Michael Rovinsky
Michael Rovinsky

Reputation: 7210

Use recursive buildNode function:

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)

Upvotes: 1

Related Questions