我有一个 Javascript 字符串数组,例如:
var array = [{
string: 'path1/path2/path3'
}, {
string: 'path1/path4/path5'
}, {
string: 'path1/path2/path6'
}, {
string: 'path10/path7'
}, {
string: 'path10/path8/path9'
}];
我需要创建一个结构如下的数据模型:
-- path1
-- path2
-- path3
-- path6
-- path4
-- path5
-- path10
-- path7
-- path8
-- path9
我怎样才能做到这一点?你有什么建议吗?谢谢
编辑:
我在想:
var paths = {
children = [
{
name: "path1"
children: [
{
name: "path2",
children: [
{
name: "path3",
children: []
}]
},
{
name: "path4",
children: [
{
name: "path5",
children: []
}]
}
}
],
.......
};
最佳答案
这应该让你开始:
var array = [{
string: 'path1/path2/path3'
}, {
string: 'path1/path4/path5'
}, {
string: 'path1/path2/path6'
}, {
string: 'path10/path7'
}, {
string: 'path10/path8/path9'
}];
let tree = {};
for (let {string} of array) {
let t = tree;
for (let c of string.split('/'))
t = t[c] || (t[c] = {});
}
console.log(tree);
关于javascript - 拆分数组中的字符串以创建菜单和子菜单数据结构的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189330/