gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:13:39 29 4
gpt4 key购买 nike

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

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 = ["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; }

关于javascript - 将平面数组解析为嵌套结构(树),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44781536/

29 4 0
文章推荐: c# - 当前上下文中不存在名称 'ARSubsystemManager'
文章推荐: 无法增加共享内存的大小
文章推荐: c# - 如何序列化 List 同时转义特殊字符?
文章推荐: c - c中的回文数检查