扁平化数据转数组解构
先准备一组数据
let list = [
{ id: '1', parentId: 0, name: '一级1' },
{ id: '1-1', parentId: '1', name: '二级1-1' },
{ id: '1-1-1', parentId: '1-1', name: '三级1-1-1' },
{ id: '2', parentId: 0, name: '一级2' },
{ id: '2-1', parentId: '2', name: '二级2-1' },
{ id: '2-2', parentId: '2', name: '二级2-2' },
{ id: '2-1-1', parentId: '2-1', name: '三级2-1-1' },
{ id: '2-1-2', parentId: '2-1', name: '三级2-1-2' },
{ id: '3', parentId: 0, name: '一级3' },
]
废话不多说上代码
function tranListToTreeData(list){
// 先定义两个变量
const treeList = [] //boss
const map = {}
// 建立映射关系: 目的是让我们能通过id快速找到对应的元素
// 保证每个元素都有 children ,用处储存子元素
list.forEach(item=>{
if(!item.children){
item.children = []
}
map[item.id] = item
})
// 先找父级
list.forEach(item=>{
const parent = map[item.parentId]
if(parent){
parent.children.push(item)
} else {
treeList.push(item)
}
})
return treeList
}
console.log(tranListToTreeData(list));
利用递归解决树状结构转平铺
function fn(arr) {
const flatList = []
// console.log(arr);
arr.forEach(item => {
if(item.children?.length) {
// console.log(fn(item.children))
flatList.push(...fn(item.children))
delete item.children
}
flatList.push(item)
delete item.children
})
return flatList
}
console.log(fn(arr));