将平面数组解析为嵌套结构(树)

Parse flat array into a nested structure (tree)

例如,我想解析以下数组:

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

进入:

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": []
        }
    ]
}

我认为 D3.JS 提供了一个很好的方法,但我找不到一些好的例子。

感谢您的帮助!

您可以使用嵌套散列 table 方法构建树结构。

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