簡體   English   中英

將平面數組解析為嵌套結構(樹)

[英]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提供了一個很好的方法,但是我找不到很好的例子。

謝謝你的幫助!

您可以使用嵌套哈希表方法來構建樹結構。

 var nodes = ["abcd", "aefg", "ah", "aij", "abk"], 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; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM