const data = [
{
id: 1,
text: '节点1',
parentId: 0,
children: [
{
id: 2,
text: '节点1_1',
parentId: 1
}
]
}
]
function treeToList(data){
let res=[]
const dfs=(tree)=>{
tree.forEach(item=>{
if(item.children){
dfs(item.children)
delete item.children
}
res.push(item)
})
}
dfs(data)
return res
}
let arr = [
{ id: 1, name: '部门1', pid: 0 },
{ id: 2, name: '部门2', pid: 1 },
{ id: 3, name: '部门3', pid: 1 },
{ id: 4, name: '部门4', pid: 3 },
{ id: 5, name: '部门5', pid: 4 },
{ id: 6, name: '部门6', pid: 0 },
]
function listToTree(arr){
const list = []
arr.forEach(element=>{
const chiildren_arr = arr.filter(ele => {
return element.id === ele.pid
})
if(chiildren_arr.length>0){
element.children=chiildren_arr
}
if(element.pid===0){
list.push(element)
}
})
return list
}
console.log(listToTree(arr))
树形和列表
最新推荐文章于 2024-09-07 14:37:16 发布