Since one of my hobby is oversimplification, I was bored enough to write an anonymous code in javascript to make a hierarchycal tree node from a table.
var treeTable = [
{ "id": 1, "parent": 0, "name": "Grandpa" },
{ "id": 2, "parent": 1, "name": "Dad" },
{ "id": 3, "parent": 1, "name": "Uncle" },
{ "id": 4, "parent": 2, "name": "Me!" },
{ "id": 5, "parent": 0, "name": "Grunkle" },
{ "id": 6, "parent": 5, "name": "Cousin" }
]; // sample table...
var treeData = (function dataTree(input, parent = 0) {
var ret = [];
input.forEach(function(o, i) {
if(o.parent == parent) {
o.children = dataTree(input, o.id); // make the function recursive
ret[ret.length] = o;
}
});
return ret;
})(treeTable);
console.log(treeData);
/* outputs
[
{
"id": 1,
"parent": 0,
"children": [
{
"id": 2,
"parent": 1,
"children": [
{
"id": 4,
"parent": 2,
"children": []
}
]
}, {
"id": 3,
"parent": 1,
"children": []
}
]
}, {
"id": 5,
"parent": 0,
"children": [
{
"id": 6,
"parent": 5,
"children": []
}
]
}
]
*/
That's it. Or don't make it anonymous, depending on your use case.