后台返回扁平数据如下:
let rootList1 = [
{ id: 1, parent: null, text: "菜单1" },
{ id: 11, parent: 1, text: "菜单1-1" },
{ id: 111, parent: 11, text: "菜单1-1-1" },
{ id: 112, parent: 11, text: "菜单1-1-2" },
{ id: 12, parent: 1, text: "菜单1-2" },
{ id: 2, parent: null, text: "菜单2" },
{ id: 21, parent: 2, text: "菜单2-1" },
{ id: 22, parent: 2, text: "菜单2-2" },
]
let rootList2 = [
{
id: 43,
menu_name: "测试任务",
menu_href: "6",
menu_icon: "el-icon-lx-edit",
tree_sort: 600,
tree_level: 1,
is_show: 1,
status: 0,
remarks: "",
parent: null,
},
{
id: 44,
menu_name: "待领样",
menu_href: "waitGetSamples",
menu_icon: "",
tree_sort: 610,
tree_level: 2,
is_show: 1,
status: 0,
remarks: "",
parent: 43,
},
{
id: 45,
menu_name: "待测试",
menu_href: "waitTest",
menu_icon: "",
tree_sort: 620,
tree_level: 2,
is_show: 1,
status: 0,
remarks: "",
parent: 43,
},
{
id: 46,
menu_name: "测试中",
menu_href: "testInProcess",
menu_icon: "",
tree_sort: 630,
tree_level: 2,
is_show: 1,
status: 0,
remarks: "",
parent: 43,
},
{
id: 47,
menu_name: "数据审核",
menu_href: "7",
menu_icon: "el-icon-lx-punch",
tree_sort: 700,
tree_level: 1,
is_show: 1,
status: 0,
remarks: "",
parent: null,
},
{
id: 48,
menu_name: "数据审理",
menu_href: "dataAuditing",
menu_icon: "",
tree_sort: 710,
tree_level: 2,
is_show: 1,
status: 0,
remarks: "",
parent: 47,
},
{
id: 49,
menu_name: "异常处理",
menu_href: "exceptionHandling",
menu_icon: "",
tree_sort: 720,
tree_level: 2,
is_show: 1,
status: 0,
remarks: "",
parent: 47,
},
{
id: 50,
menu_name: "样品异常",
menu_href: "SamplesAbnormal",
menu_icon: "",
tree_sort: 721,
tree_level: 3,
is_show: 1,
status: 0,
remarks: "",
parent: 49,
},
{
id: 51,
menu_name: "测试数据异常",
menu_href: "testDataException",
menu_icon: "",
tree_sort: 722,
tree_level: 3,
is_show: 1,
status: 0,
remarks: "",
parent: 49,
},
{
id: 52,
menu_name: "设备异常处理",
menu_href: "deviceExceptionHandling",
menu_icon: "",
tree_sort: 723,
tree_level: 3,
is_show: 1,
status: 0,
remarks: "",
parent: 49,
},
]
一、递归方法:
function getTreeList(rootList, id, list) {
for (const i of rootList) {
if (i.parent === id) {
list.push(i)
}
}
for (const j of list) {
j.children = []
getTreeList(rootList, j.id, j.children)
// 去除 children: []
if (j.children.length === 0) {
delete j.children
}
}
return list
}
使用并打印出来:
const res = getTreeList(rootList, null, [])
console.log(res)
const res2 = getTreeList(rootList2, null, [])
console.log(res2)