JSFiddle - React, Tailwind, and code Playground
by sijoma
JavaScript
var data = [
{ "name" : "ABC", "parent":"DEF", "relation": "ghi", "depth": 1 },
{ "name" : "DEF", "parent":"ABC", "relation": "null", "depth": 0 },
{ "name" : "new_name", "parent":"ABC", "relation": "rel", "depth": 2 },
{ "name" : "new_name2", "parent":"ABC", "relation": "foo", "depth": 2 },
{ "name" : "Foo", "parent":"DEF", "relation": "rel", "depth": 2 },
{ "name" : "Bar", "parent":"null", "relation": "rel", "depth": 2 }
];
// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
// create the tree array
var tree = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
tree.push(node);
}
});
// show what we've got
d3.select('body').append('pre')
.text(JSON.stringify(tree, null, ' '));