- 原始数据
let data = [
{
id: 1,
name: '目录1',
parentId: 0
},
{
id: 2,
name: '目录1-1',
parentId: 1
},
{
id: 3,
name: '目录1-2',
parentId: 1
},
{
id: 4,
name: '目录1-3',
parentId: 1
},
{
id: 5,
name: '目录1-1-1',
parentId: 2
},
{
id: 6,
name: '目录1-1-2',
parentId: 2
},
{
id: 7,
name: '目录2',
parentId: 0
},
{
id: 8,
name: '目录2-1',
parentId: 7
},
{
id: 9,
name: '目录2-2',
parentId: 7
},
{
id: 10,
name: '目录2-1-1',
parentId: 8
},
{
id: 11,
name: '目录2-1-1-1',
parentId: 10
},
{
id: 12,
name: '目录2-1-2',
parentId: 8
}
]
2.数据转化
先将给定的数据处理成通过children属性串联的结构,方便递归处理
const map = {}
data.forEach(item=>{
map[item.id] = item
})
const result = []
data.forEach(item=>{
const parent = map[item.parentId]
if(parent){
parent.children = parent.children || []
parent.children.push(item)
}else{
result.push(item)
}
})
3.递归生成dom元素
// 递归处理
function createNode(data, root){
data.forEach(item=>{
const detailsEle = document.createElement('details')
const summaryEle = document.createElement('summary')
summaryEle.innerHTML = item.name
detailsEle.appendChild(summaryEle)
root.appendChild(detailsEle)
if(item.children?.length){
createNode(item.children, detailsEle)
}
})
}
createNode(result, document.getElementById('tree'))