Open qappleh opened 3 years ago
getTree(data) {
const backArr = JSON.parse(JSON.stringify(data)).reverse()
let childArr = []
let treeArr = []
function recursion(arr1) {
if (arr1.length === 1) {
arr1[0].children = childArr
treeArr = JSON.parse(JSON.stringify(arr1))
} else {
if (childArr.length) {
arr1[0].children = childArr
childArr = []
}
childArr.push(arr1.shift())
recursion(arr1)
}
}
recursion(backArr)
return treeArr
},
interface ListItem {
id: number
name: string
parent: number | null
}
interface TreeItem {
id: number
name: string
children: TreeItem[]
}
function list2tree(list: ListItem[]): TreeItem[] {
const temp = {} as { [id: number]: TreeItem }
const tree = [] as TreeItem[]
// 临时储存
list.forEach(({ id, name }) => {
temp[id] = { id, name, children: [] }
})
// 遍历处理
list.forEach(({ id, parent }) => {
if (parent === null) {
tree.push(temp[id])
} else if (temp[parent]) {
temp[parent].children.push(temp[id])
}
})
return tree
}
测试
const list = [
{
name: '文本1',
parent: null,
id: 1,
},
{
name: '文本2',
id: 2,
parent: 1,
},
{
name: '文本3',
parent: 2,
id: 3,
},
]
const tree = list2tree(list)
console.log(JSON.stringify(tree, undefined, 2))
输出
[
{
"id": 1,
"name": "文本1",
"children": [
{
"id": 2,
"name": "文本2",
"children": [
{
"id": 3,
"name": "文本3",
"children": []
}
]
}
]
}
]