function listToTree (srcList) {
let destList = []
srcList.forEach(path => {
let pathList = path.split('-')
let levelList = destList
for (let name of pathList) {
let obj = levelList.find(item => item.name == name)
if (!obj) {
obj = { name, children: [] }
levelList.push(obj)
}
levelList = obj.children
}
})
return destList
}
测试:
let srcList = ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
let result = listToTree(srcList)
console.log(JSON.stringify(result, null, 2))
输出:
[
{
"name": "动物",
"children": [
{
"name": "昆虫",
"children": [
{
"name": "蚂蚁",
"children": []
},
{
"name": "蝴蝶",
"children": []
}
]
}
]
},
{
"name": "植物",
"children": [
{
"name": "草",
"children": [
{
"name": "绿色",
"children": []
}
]
},
{
"name": "花",
"children": [
{
"name": "红色",
"children": []
}
]
}
]
}
]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…