2025-03-29 15:10:08 +08:00
|
|
|
|
// TODO @芋艿:1)代码优化;2)是不是抽到公共的?
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 构造树型结构数据
|
|
|
|
|
|
* @param {*} data 数据源
|
|
|
|
|
|
* @param {*} id id字段 默认 'id'
|
|
|
|
|
|
* @param {*} parentId 父节点字段 默认 'parentId'
|
|
|
|
|
|
* @param {*} children 孩子节点字段 默认 'children'
|
|
|
|
|
|
*/
|
2025-04-07 17:31:38 +08:00
|
|
|
|
export const handleTree = (
|
|
|
|
|
|
data: any[],
|
|
|
|
|
|
id?: string,
|
|
|
|
|
|
parentId?: string,
|
|
|
|
|
|
children?: string,
|
|
|
|
|
|
) => {
|
2025-03-29 15:10:08 +08:00
|
|
|
|
if (!Array.isArray(data)) {
|
2025-04-07 17:31:38 +08:00
|
|
|
|
console.warn('data must be an array');
|
|
|
|
|
|
return [];
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
|
|
|
|
|
const config = {
|
|
|
|
|
|
id: id || 'id',
|
|
|
|
|
|
parentId: parentId || 'parentId',
|
2025-04-07 17:31:38 +08:00
|
|
|
|
childrenList: children || 'children',
|
|
|
|
|
|
};
|
2025-03-29 15:10:08 +08:00
|
|
|
|
|
2025-04-07 17:31:38 +08:00
|
|
|
|
const childrenListMap: any = {};
|
|
|
|
|
|
const nodeIds: any = {};
|
|
|
|
|
|
const tree: any[] = [];
|
2025-03-29 15:10:08 +08:00
|
|
|
|
|
|
|
|
|
|
for (const d of data) {
|
2025-04-07 17:31:38 +08:00
|
|
|
|
const parentId = d[config.parentId];
|
|
|
|
|
|
if (childrenListMap[parentId] === null) {
|
|
|
|
|
|
childrenListMap[parentId] = [];
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
2025-04-07 17:31:38 +08:00
|
|
|
|
nodeIds[d[config.id]] = d;
|
|
|
|
|
|
childrenListMap[parentId].push(d);
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for (const d of data) {
|
2025-04-07 17:31:38 +08:00
|
|
|
|
const parentId = d[config.parentId];
|
|
|
|
|
|
if (nodeIds[parentId] === null) {
|
|
|
|
|
|
tree.push(d);
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for (const t of tree) {
|
2025-04-07 17:31:38 +08:00
|
|
|
|
adaptToChildrenList(t);
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-07 17:31:38 +08:00
|
|
|
|
function adaptToChildrenList(o: any) {
|
2025-03-29 15:10:08 +08:00
|
|
|
|
if (childrenListMap[o[config.id]] !== null) {
|
2025-04-07 17:31:38 +08:00
|
|
|
|
o[config.childrenList] = childrenListMap[o[config.id]];
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
|
|
|
|
|
if (o[config.childrenList]) {
|
|
|
|
|
|
for (const c of o[config.childrenList]) {
|
2025-04-07 17:31:38 +08:00
|
|
|
|
adaptToChildrenList(c);
|
2025-03-29 15:10:08 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-07 17:31:38 +08:00
|
|
|
|
return tree;
|
|
|
|
|
|
};
|