Browse Source

add: list convert to tree

dev
powersir 1 year ago
parent
commit
1fefb85f24
2 changed files with 25 additions and 2 deletions
  1. +4
    -2
      src/layout/index.tsx
  2. +21
    -0
      src/utils/utils.ts

+ 4
- 2
src/layout/index.tsx View File

@@ -18,7 +18,8 @@ import Content from './content';
import userService from '@/request/service/user'; import userService from '@/request/service/user';
import authService from '@/request/service/auth'; import authService from '@/request/service/auth';
import { useRequest } from "@/hooks/use-request"; import { useRequest } from "@/hooks/use-request";
// import menuData from '../../mock/menu.json'




const BasicLayout: React.FC = () => { const BasicLayout: React.FC = () => {


@@ -103,7 +104,8 @@ const BasicLayout: React.FC = () => {
}) })
} }
} }
menuList.data.forEach(item => fixAndPushMenu(item))
menuList.data.forEach(item => fixAndPushMenu(item));

setMenus(menuList.data) //([...formatedMenus, ...menuList.data]); setMenus(menuList.data) //([...formatedMenus, ...menuList.data]);
console.log('components', components); console.log('components', components);
replaceRoutes('*', [ replaceRoutes('*', [


+ 21
- 0
src/utils/utils.ts View File

@@ -10,3 +10,24 @@ export function getParamsBySearchParams<T = any>(query: URLSearchParams) {
); );
return params as T; return params as T;
} }


export function convertToTree<T = any>(source: T[], keyExtra: (item: T) => string | number, parentKeyExtra: (item: T) => string | number): T[] {
const sourceMap: {[key: string | number]: T} = {};
for(const item of source) {
const children = (item as any)['children'] ? (item as any)['children'] : [];
(item as any).children = children;
sourceMap[keyExtra(item)] = item;
}
const rootKeys = [];
for(const item of source) {
const parentKey = parentKeyExtra(item);
if(parentKey in sourceMap) {
(sourceMap[parentKey] as any).children?.push(item)
} else {
rootKeys.push(keyExtra(item))
}
}
return rootKeys.map(key => sourceMap[key])
}

Loading…
Cancel
Save