将树结构拍平为一维数组
/**
* @description 使用递归处理路由菜单,生成一维数组,做菜单权限判断
* @param {Array} menuList 所有菜单列表
* @param {Array} newArr 菜单的一维数组
* @return array
*/
export function handleRouter(routerList: Menu.MenuOptions[], newArr: string[] = []) {
routerList.forEach((item: Menu.MenuOptions) => {
typeof item === "object" && item.path && newArr.push(item.path);
item.children && item.children.length && handleRouter(item.children, newArr);
});
return newArr;
}
方法 2
// const arr1 = [
// {
// id: 1,
// text: "节点1",
// parentId: 0,
// children: [
// {
// id: 2,
// text: "节点1_1",
// parentId: 1,
// },
// ],
// },
// // ...
// ]
function treeToList (arr) {
let res = [];
const toList = (tree) => {
tree.forEach((item) => {
if(item.children) {
toList(item.children)
delete item.children
}
res.push(item)
})
}
toList(arr)
return res
}