fix: type error

pull/71/head
xingyu4j 2025-04-07 17:31:38 +08:00
parent 81fe98b62e
commit 52ca67b909
1 changed files with 27 additions and 22 deletions

View File

@ -6,51 +6,56 @@
* @param {*} parentId 'parentId' * @param {*} parentId 'parentId'
* @param {*} children 'children' * @param {*} children 'children'
*/ */
export const handleTree = (data: any[], id?: string, parentId?: string, children?: string) => { export const handleTree = (
data: any[],
id?: string,
parentId?: string,
children?: string,
) => {
if (!Array.isArray(data)) { if (!Array.isArray(data)) {
console.warn('data must be an array') console.warn('data must be an array');
return [] return [];
} }
const config = { const config = {
id: id || 'id', id: id || 'id',
parentId: parentId || 'parentId', parentId: parentId || 'parentId',
childrenList: children || 'children' childrenList: children || 'children',
} };
const childrenListMap = {} const childrenListMap: any = {};
const nodeIds = {} const nodeIds: any = {};
const tree: any[] = [] const tree: any[] = [];
for (const d of data) { for (const d of data) {
const parentId = d[config.parentId] const parentId = d[config.parentId];
if (childrenListMap[parentId] == null) { if (childrenListMap[parentId] === null) {
childrenListMap[parentId] = [] childrenListMap[parentId] = [];
} }
nodeIds[d[config.id]] = d nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d) childrenListMap[parentId].push(d);
} }
for (const d of data) { for (const d of data) {
const parentId = d[config.parentId] const parentId = d[config.parentId];
if (nodeIds[parentId] == null) { if (nodeIds[parentId] === null) {
tree.push(d) tree.push(d);
} }
} }
for (const t of tree) { for (const t of tree) {
adaptToChildrenList(t) adaptToChildrenList(t);
} }
function adaptToChildrenList(o) { function adaptToChildrenList(o: any) {
if (childrenListMap[o[config.id]] !== null) { if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]] o[config.childrenList] = childrenListMap[o[config.id]];
} }
if (o[config.childrenList]) { if (o[config.childrenList]) {
for (const c of o[config.childrenList]) { for (const c of o[config.childrenList]) {
adaptToChildrenList(c) adaptToChildrenList(c);
} }
} }
} }
return tree return tree;
} };