Skip to content

Instantly share code, notes, and snippets.

@harold
Last active April 20, 2020 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save harold/e373e0a31725c36cfe3aa528cb8e47e0 to your computer and use it in GitHub Desktop.
Save harold/e373e0a31725c36cfe3aa528cb8e47e0 to your computer and use it in GitHub Desktop.
Simplest Hierarchy from CSV
license: mit
id name parent
1 Food
2 Entertainment
3 Apple 1
4 Granny Smith (eww) 3
5 Honeycrisp (yum) 3
6 Pizza 1
7 Movies 2
8 Star Wars 7
9 Spider Man 7
10 Video Games 2
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-dsv.v1.min.js"></script>
<script src="https://d3js.org/d3-fetch.v1.min.js"></script>
<style>
* {font-family:sans-serif}
ul {padding-left:20px}
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// Recrusive helper for building the json hierarchy
function addChildren(node, allItems) {
node.children = []
for(let i=0; i<allItems.length; i++) {
let item = allItems[i]
if(node.id == item.parent) {
node.children.push(item)
addChildren(item, allItems)
}
}
}
// Another recursive function to d3 the tree
function d3Node(node, parent) {
let ul = parent.append("ul")
ul.append("li").text(node.name)
for(let i=0; i<node.children.length; i++) {
let child = node.children[i]
d3Node(child, ul)
}
}
d3.csv("data.csv").then(function(parsedCSV) {
console.log("===========")
console.log("Parsed CSV:")
console.dir(parsedCSV)
let root = {name: "root", id: ""}
addChildren(root, parsedCSV)
console.log("==============")
console.log("JSON Hierarchy:")
console.dir(root)
var div = d3.select("body").append("div")
d3Node(root, div)
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment