import path from 'path' const utils = { /** * @description 铺平树形结构为一维数组 * @function flatten * @param {Object|Object[]} arr 树节点或树节点数组 * @param {string} childKey=children 树子节点数组属性 * @returns {Object[]} */ flatten: (arr, childKey = 'children') => { const flattenArray = (arr, childKey) => { if (Array.isArray(arr)) return Array.prototype.concat.apply( [], arr.map((i) => flattenArray(i, childKey)) ) else if (Reflect.has(arr, childKey)) return [arr, ...flattenArray(arr[childKey], childKey)] return [arr] } return flattenArray(arr, childKey) }, /** * @description 去除菜单中的按钮,符合渲染左侧菜单的树型结构,直接修改源数据,并加上完整的路径 * @function filterMenu * @param {array} array 后台返回的包括按钮的树形结构 */ filterMenu: (array, superPath = '/') => { array.forEach((item) => { item.fullPath = utils.getFullPath(superPath, item.menuHref) item.iconClass = item.menuIcon || null if (item.children && item.children.length > 0) { if (item.children.find((child) => child.menuType === 'BUTTON')) { item.children = [] } else { utils.filterMenu(item.children, item.fullPath) } } }) }, /** * @description 将后台返回的树型结构转化为只包含叶子菜单的一维数组结构并去除按钮,且加上该叶子菜单的完整路径 * @function filterMenu2LeafArray * @param {array} menus 后台返回的包括按钮的树形结构 * @param {array} init 用于递归的返回值 * @param {string} superPath 上级路由,用于递归时拼接完整路径 * @return {Array} 返回符合要求的一维数组 */ filterMenu2LeafArray: (menus, init = [], superPath = '/') => { menus.forEach((menu) => { if (menu && menu.children && menu.children.length > 0) { if (menu.children.find((child) => child.menuType === 'BUTTON')) { init = init.concat({ ...menu, fullPath: utils.getFullPath(superPath, menu.menuHref), }) } else { init = utils.filterMenu2LeafArray( menu.children, init, utils.getFullPath(superPath, menu.menuHref) ) } } else { init = init.concat({ ...menu, fullPath: utils.getFullPath(superPath, menu.menuHref), }) } }) return init }, /** * @description 将后台返回的树型结构转化为只包含按钮权限的一维数组 * @param {array} menus 后台返回的包括按钮的树形结构 * @param {array} init 用于递归的返回值 * @return {array} 返回符合要求的一维数组 */ filterMenuPermissions: (menus, init = []) => { menus.forEach((menu) => { if (menu && menu.menuPermission) { if (!init.includes(menu.menuPermission)) { init.push(menu.menuPermission) } } if (menu && menu.children && menu.children.length > 0) { init = utils.filterMenuPermissions(menu.children, init) } }) return init }, getFullPath: (superPath, currentPath) => { currentPath = currentPath || '' if (currentPath.startsWith('http')) { return currentPath } return currentPath.startsWith('/') ? currentPath : path.join(superPath, currentPath).replace(/\\/g, '/') }, } export default utils