type ConfigProps = Partial<{ idKey: string; parentIdKey: string; childrenKey: string; }>; // 将扁平的数组转化为树形结构的数组 export function getTreeFromList( targetList: T[], configs: ConfigProps, ): T[] { const { idKey = 'id', parentIdKey = 'pid', childrenKey = 'children', } = configs; // 初始化结果数组,并判断输入数据的格式 let result: any[] = []; if (!Array.isArray(targetList)) { return result; } // 避免目标列表被改造,导致多次执行会有异常 const newTargetList: any[] = JSON.parse(JSON.stringify(targetList)); // 使用map,将当前对象的id与当前对象对应存储起来 let map: any = {}; newTargetList.forEach((item) => { map[item[idKey]] = item; }); newTargetList.forEach((item) => { let parent = map[item[parentIdKey]]; if (parent) { (parent[childrenKey] || (parent[childrenKey] = [])).push(item); } else { result.push(item); } }); return result; } // 将树形结构转为扁平数组结构 export function getListFromTree(targetList: T[]): T[] { return targetList.reduce((ret: T[], cur: T) => { // @ts-ignore const { children, ...rest } = cur; return [...ret, rest, ...getListFromTree(children || [])]; }, []); }