Reputation: 636
I have a tree structure like the following:
{
"7": ["3", "8"],
"3": ["2", "4", "1"],
"4": ["5", "6"],
"8": ["12", "13"]
}
This dictionary simply means that the root node of the tree is 7(as it is not a child of any other node) which has two children 3 and 8 while 3 has three children(2, 4, 1) and 8 has two children(12, 13). 3 has a child 4 which has two children(5,6).
My problem is that I need a dynamic tree generator as I will have different tree(And they will not be binary tree!) structure every time I shall run the code. My code is in python and I want show the tree in web.
Is there any javascript library which I can use to draw this tree?
Upvotes: 1
Views: 1188
Reputation: 386578
You could iterate the keys of the object and build a new temporary object with all relations. Then delete from the root array all keys with predecessor.
Return a new object with the root key and all childrens.
var data = { 7: ["3", "8"], 3: ["2", "4", "1"], 4: ["5", "6"], 8: ["12", "13"] },
tree = function (object) {
var root = Object.keys(data),
o = Object.create(null),
r = Object.create(null);
root.slice().forEach(function (k) {
o[k] = o[k] || {};
data[k].forEach(function (a) {
var p = root.indexOf(a);
if (p !== -1) {
root.splice(p, 1);
}
o[a] = o[a] || {};
o[k][a] = o[a];
});
});
r[root] = o[root];
return r;
}(data);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1