Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 将树结构拍平为一维数组

将树结构拍平为一维数组

/**
 * @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
	}

Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人