Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format.
If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP/SQL.
Check out the original code here: Original code
I've been working on creating a similar effect with my own data. I've made some progress, and you can actually run the sample code to see the desired structure.
<script>
var data = [
{ "name" : "A", "parent":"null" },
{ "name" : "J", "parent":"A"},
{ "name" : "I", "parent":"A" },
{ "name" : "G", "parent":"A" },
{ "name" : "H", "parent":"A" },
{ "name" : "Cr", "parent":"B" },
{ "name" : "D", "parent":"Cr" },
{ "name" : "E", "parent":"Cr" },
{ "name" : "H", "parent":"A" },
{ "name" : "F", "parent":"Cr"},
{ "name" : "B", "parent":"A" }
];
// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
// create the tree
var tree = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child
(parent.children || (parent.children = []))
// add node
.push(node);
} else {
// null or missing
tree.push(node);
}
});
d3.select('body').append('pre').text(JSON.stringify(tree, null, ' '));
Now, I'm facing a challenge in integrating these two components seamlessly.
It's probably something simple, but staring at code and rewriting it after consuming copious amounts of coffee is starting to take its toll.
If any of you experts out there have any hints or suggestions, please feel free to share them. Any modifications or recreations of the existing code are more than welcome. Thank you for taking the time to read through this!