Files
iot-device-management-frontend/apps/web-antd/src/utils/tree.ts

62 lines
1.4 KiB
TypeScript
Raw Normal View History

// 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,
) => {
if (!Array.isArray(data)) {
2025-04-07 17:31:38 +08:00
console.warn('data must be an array');
return [];
}
const config = {
id: id || 'id',
parentId: parentId || 'parentId',
2025-04-07 17:31:38 +08:00
childrenList: children || 'children',
};
2025-04-07 17:31:38 +08:00
const childrenListMap: any = {};
const nodeIds: any = {};
const tree: any[] = [];
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-04-07 17:31:38 +08:00
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
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);
}
}
for (const t of tree) {
2025-04-07 17:31:38 +08:00
adaptToChildrenList(t);
}
2025-04-07 17:31:38 +08:00
function adaptToChildrenList(o: any) {
if (childrenListMap[o[config.id]] !== null) {
2025-04-07 17:31:38 +08:00
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) {
for (const c of o[config.childrenList]) {
2025-04-07 17:31:38 +08:00
adaptToChildrenList(c);
}
}
}
2025-04-07 17:31:38 +08:00
return tree;
};