在这里插入代码片
// 数组转树形
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; // 删除 空 chidren
}
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, '树形转一维数组')
前端 递归 数组转树形,树形转数组
最新推荐文章于 2024-07-30 16:49:30 发布