I have a flat JSON array and try to format it for a tree representation in D3.js
v7 using the below code. I grouped the data and then used hierarchy to make the link and nodes as is described in the documentation but when I make the graph it produces an empty root and last children.
How should I format the data to get the tree in the below graph?
CodePudding user response:
If we assume that there is only one project at the top, then it would be better not to group by project. Similarly, since the divisions are leaf-nodes, it would be better not to group by division.
groupedData = d3.group(
data,
(d) => d.project_nr,
(d) => d.department
);
However now we're missing the "project" name in the root node, and the division name in the leaf nodes. These can be retrieved by using:
({ data }) => Array.isArray(data) ? data[0] || "project" : data.devision
Here's a notebook with the complete code: https://observablehq.com/@recifs/data-to-tree--support