我有一个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: []
}]
}
}
],
.......
};
答案 0 :(得分:2)
这应该让你开始:
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);