javascriptd3.jstree-structure

Parse flat array into a nested structure (tree)


For example, I'd like to parse the following array:

var array1 = ["a.b.c.d", "a.e.f.g", "a.h", "a.i.j", "a.b.k"]

into:

var json1 = {
    "node": "a",
    "leaf": false,
    "children": [{
            "node": "b",
            "leaf": false,
            "children": [{
                    "node": "c",
                    "children": [{
                        "node": "d",
                        "leaf": true,
                        "children": []
                    }]
                },
                {
                    "node": "h",
                    "leaf": true,
                    "children": []
                }
            ]
        },
        {
            "node": "e",
            "leaf": false,
            "children": [{
                "node": "f",
                "leaf": true,
                "children": []
            }]
        },
        {
            "node": "g",
            "leaf": true,
            "children": []
        }
    ]
}

I think that D3.JS provides a good way to do this but I cannot find some good example.

Thanks for any help!


Solution

  • You could use a nested hash table approach for building a tree structure.

    var nodes = ["a.b.c.d", "a.e.f.g", "a.h", "a.i.j", "a.b.k"],
        result = [];
    
    nodes.forEach(function (a) {
        a.split('.').reduce(function (r, k, i, kk) {
            if (!r[k]) {
                r[k] = { _: [] };
                r._.push({ node: k, leaf: i + 1 === kk.length, children: r[k]._ });
            }
            return r[k];
        }, this);
    }, { _: result });
    
    console.log(result[0]);
    .as-console-wrapper { max-height: 100% !important; top: 0; }