我有一个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);