1

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?

4
  • 2
    asking for a library is ot. Commented Mar 3, 2017 at 12:15
  • There are any number of them; I'd just start by looking. Although if you want to draw pathological trees like this one, where nodes don't exist, you may run into troubles. Commented Mar 3, 2017 at 12:17
  • @DaveNewton, the tree should be a valid one, I can assure that. :) Commented Mar 3, 2017 at 12:19
  • This might help: stackoverflow.com/questions/6344318/… Commented Mar 3, 2017 at 12:25

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.