前端數(shù)組轉(zhuǎn)為樹結(jié)構(gòu)在我們平時(shí)開發(fā)中經(jīng)常遇到同诫,主要用到了遞歸回調(diào)。下面的做法可提供一種轉(zhuǎn)換思路耿戚。
我們拿到的數(shù)據(jù)格式是
let list= [
{ id: '1', parentId: '', name: '1' },
{ id: '2', parentId: '', name: '2' },
{ id: '3', parentId: '1', name: '3' },
{ id: '4', parentId: '3', name: '4' },
{ id: '5', parentId: '2', name: '5' },
{ id: '6', parentId: '5', name: '6' },
{ id: '7', parentId: '6', name: '7' },
]
我們想要用來(lái)渲染頁(yè)面的格式是
newList = [
{
name: '1',
id: '1',
parentId: '',
child: [
{
id: '3',
parentId: '1',
name: '3',
child: [
{
id: '4',
parentId: '3',
name: '4',
child: []
}
]
}
]
},
{
id: '2',
parentId: '',
name: '2',
child: [
{
id: '5',
parentId: '2',
name: '5',
child: [
{
id: '6',
parentId: '5',
name: '6',
child: [
{
id: '7',
parentId: '6',
name: '7',
child: []
},
]
},
],
},
]
}
]
第一步窒典,找出最上面的節(jié)點(diǎn)蟆炊。很明顯的parentId為空的數(shù)據(jù)是最上面的節(jié)點(diǎn)。
// 首先對(duì)數(shù)據(jù)深拷貝一份數(shù)據(jù)崇败,因?yàn)橄旅娴奶幚頃?huì)影響原數(shù)組
let curList = JSON.parse(JSON.stringify(list))
let newList = []
for(let i = 0; i < curList.length; i++) {
if(!curList[i].parentId) {
curList[i].child = []
newList.push(curList[i])
curList.splice(i, 1) // 篩選后做刪除
i--
}
}
第二步盅称,找出第二節(jié)點(diǎn)加到父節(jié)點(diǎn)child數(shù)組里面
travChild(curList, newList)
function travChild(curList, newList) {
for(let i = 0; i < curList.length; i++) {
for(let j = 0; j < newList.length; j++) {
if (curList[i].parentId === newList[j].id) {
curList[i].child = []
newList[j].child.push(curList[i])
curList.splice(i, 1)
}
}
}
// 第三步,找出第三節(jié)點(diǎn)后室,加到第二節(jié)點(diǎn)
let twinNode = treeEndNode(newList) // 獲取第二節(jié)點(diǎn)
if (curList.length) {
travChild(curList, twinNode)
}
// 第n步缩膝,回調(diào)第三的步驟
}
function treeEndNode(tree, twinList = []) {
tree.map(item => {
if (item.child.length) {
treeEndNode(item.child, twinList)
} else {
twinList.push(item)
}
})
return twinList
}
newList 就是我們的結(jié)果。
步驟二三也可以這樣處理岸霹,可以防止curList.length的值不為空的時(shí)候無(wú)限循環(huán)回調(diào)
function travChild(curList, newList) {
for(let i = 0; i < curList.length; i++) {
for(let j = 0; j < newList.length; j++) {
if (curList[i].parentId === newList[j].id) {
curList[i].child = []
newList[j].child.push(curList[i])
curList.splice(i, 1)
}
}
}
// 第n層
newList.map(item => {
if (item.child.length) {
travChild(curList,item.child)
}
})
}