export function arrayToTreeByLevelCode(data, levelField, childrenField) { if (!Array.isArray(data)) { console.error("Invalid data: data is not an array", data); return []; } const tree = []; const map = new Map(); // 初始化 Map,每个 levelCode 对应一个节点对象 data.forEach(item => { map.set(item[levelField], { ...item, [childrenField]: [] }); }); data.forEach(item => { const node = map.get(item[levelField]); const parentKey = item[levelField].split('.').slice(0, -1).join('.'); // 获取父节点的 levelCode if (parentKey && map.has(parentKey)) { // 如果有父节点,添加到父节点的 children 数组中 map.get(parentKey)[childrenField].push(node); } else { // 没有父节点,说明是根节点 tree.push(node); } }); return tree; }