Generating a Tree Diagram from 'Flat' Data

Learn how to generate a tree diagram using "flat" data.

We'll cover the following

Tree diagrams are a fantastic way of displaying information. But one of the drawbacks (to the examples we’ve been using so far) is the need to have your data encoded hierarchically.

Flat data

Most data in a raw form will be flat. That is to say, it won’t be formatted as an array with the parent-child relationships. Instead, it will be a list of objects (which we will want to turn into nodes) that might describe the relationship to each other, but they won’t be encoded that way. For example, the following is the flat representation of the example data we have been using thus far.

  {"name": "Top Level", "parent": null},
  {"name": "Level 2: A", "parent": "Top Level" },
  {"name": "Level 2: B", "parent": "Top Level" },
  {"name": "Son of A", "parent": "Level 2: A" },
  {"name": "Daughter of A", "parent": "Level 2: A" }

It is actually fairly simple and consists of only the name of the node and the name of its parent node. It’s easy to see how this data could be developed into a hierarchical form, but it would take a little time. For a larger data set, that would be tiresome.

Luckily, computers are built for shuffling data about, and with the advent of v4 of D3.js, we now have the d3.stratify operator that will convert flat data into a hierarchy suitable for use in our tree diagram.

We will be using the simple example that we started with at the start of the chapter, and the first change we need to make is to replace our original data (treeData) with our flat data array:

Get hands-on with 1200+ tech skills courses.