dj3 tree from flat array

by taufek

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="tree">

</div>

CSS

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}

JavaScript

const data = [{
    "id": 1,
    "full_name": "Jack Dorsey",
    "role": "CEO",
    "manager_id": ""
  },
  {
    "id": 2,
    "full_name": "Michael Montano",
    "role": "Engineering Lead",
    "manager_id": 1
  },
  {
    "id": 3,
    "full_name": "Kayvon Beykpour",
    "role": "Product Lead",
    "manager_id": 1
  },
  {
    "id": 4,
    "full_name": "Joy Su",
    "role": "VP Engineering",
    "manager_id": 2
  },
  {
    "id": 5,
    "full_name": "Nick Turnow",
    "role": "Platform Lead",
    "manager_id": 2
  },
  {
    "id": 6,
    "full_name": "Keith Coleman",
    "role": "VP Product",
    "manager_id": 3
  },
  {
    "id": 7,
    "full_name": "Lakshmi Shankar",
    "role": "Sr Director, Strategy & Operations",
    "manager_id": 3
  },
];


const dataMap = data.reduce(function(map, node) {
  map[node.id] = node;
  return map;
}, {});


// create the tree array
const treeData = [];
data.forEach(function(node) {
  // add to parent
  var manager = dataMap[node.manager_id];
  if (manager) {
    // create child array if it doesn't exist
    (manager.children || (manager.children = []))
    // add node to child array
    .push(node);
  } else {
    // parent is null or missing
    treeData.push(node);
  }
});

var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 960 - margin.right - margin.left,
  height = 500 - margin.top - margin.bottom;

var i = 0;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("#tree").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];

update(root);

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for...