在这里插入代码片
let rootList = [{
id: 1,
parent: null,
text: '菜单1'
},
{
id: 2,
parent: null,
text: '菜单1'
},
{
id: 11,
parent: 1,
text: '菜单1-1'
},
{
id: 12,
parent: 1,
text: '菜单1-2'
},
{
id: 21,
parent: 2,
text: '菜单2-1'
},
{
id: 23,
parent: 2,
text: '菜单2-2'
},
{
id: 33,
parent: 23,
text: '菜单3-23'
},
]
function getTreeList(rootList, id, list) {
for (let s of rootList) {
if (s.parent == id) {
list.push(s)
}
}
for (let i of list) {
i.children = getTreeList(rootList, i.id, []);
if(!i.children.length) delete i.children;
}
return list
}
const res = getTreeList(rootList, null, [])
console.log(res, '数组转树形')
let arrc = [
{
id:1,
parent:null,
text:'第一',
children:[
{
id: 11,
parent:1,
text:'第一yi',
children:[
{
id:12,
parent:11,
text:'第一yier',
}
],
}
],
},
{
id:2,
parent:null,
text:'第二',
children:[
{
id:22,
parent:2,
text:'第二yi',
children:[
{
id:32,
parent:22,
text:'第二yier'
}
]
}
]
}
]
function treeArr(arr) {
let arrs = []
for (let s of arr) {
if(s.children){
arrs.push(...treeArr(s.children))
delete s.children
}
arrs.push(s)
}
return arrs
}
const aff = treeArr(arrc)
console.log(aff, '树形转一维数组')