You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

29 lines
846 B

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;
}