1

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!

luthien
  • 1,285
  • 3
  • 15
  • 26
  • Have a look at https://stackoverflow.com/questions/44679971/create-nested-object-from-multiple-string-paths/44680094#44680094 – Jonas Wilms Jun 27 '17 at 13:33

1 Answers1

2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392