扁平的列表数据结构
const data = [
{
deptId: '',
deptName: '',
parentId: '',
orderNum: ''
},
...
]
符合antd的cascader的options的数据结构
[
{
label: '',
value: '',
children: [
{
label: '',
value: '',
children: [
...
]
}
],
...
}
]
附加逻辑:按orderNum对同级部门进行排序
步骤
1、创建一个Map集合,用于缓存所有部门节点,方便后续通过deptId快速查找对应的节点(避免多次遍历数组)
const deptMap = new Map();
2、最终要返回的树形结构数组,用来存放所有顶级部门(parentId = 0 或 ‘0’)
const treeData = [];
3、第一次遍历扁平的列表数组,为每个部门创建节点对象,并存入Map
data.forEach(i => {
const node = {
value: i.deptId,
label: i.deptName,
parentId: i.parentId,
children: []
}
deptMap.set(i.deptId, node);
})
4、第二次遍历扁平的列表数组,根据parentId建立父子节点的关联关系
data.forEach(i => {
const currentNode = deptMap.get(i.deptId);
const parentId = i.parentId;
if(parentId === 0 || parentId === '0') {
treeData.push(currentNode);
}else {
const parentNode = deptMap.get(parentId);
if(parentNode) {
parentNode.children.push(currentNode);
}
}
})
5、此时已经拿到cascader需要的数组treeData,再将子级部门按orderNum排列即可
const sortChildrenByOrder = (nodes) => {
nodes.forEach(i => {
i.children.sort((a, b) => {
const orderA = Number(a.orderNum || 0);
const orderB = Number(b.orderNum || 0);
return orderA - orderB;
});
sortChildrenByOrder(i.children);
})
}
sortChildrenByOrder(treeData);
完整代码
const convertDeptToCascaderData = (flatDeptData) => {
const deptMap = new Map();
const treeData = [];
flatDeptData.forEach(item => {
const node = {
value: item.deptId,
label: item.deptName,
parentId: item.parentId,
children: []
};
deptMap.set(item.deptId, node);
});
flatDeptData.forEach(item => {
const currentNode = deptMap.get(item.deptId);
const parentId = item.parentId;
if (parentId === 0 || parentId === '0') {
treeData.push(currentNode);
} else {
const parentNode = deptMap.get(parentId);
if (parentNode) {
parentNode.children.push(currentNode);
}
}
});
const sortChildrenByOrder = (nodes) => {
nodes.forEach(node => {
node.children.sort((a, b) => {
const orderA = Number(a.orderNum || 0);
const orderB = Number(b.orderNum || 0);
return orderA - orderB;
});
sortChildrenByOrder(node.children);
});
};
sortChildrenByOrder(treeData);
return treeData;
};
示例数据
const flatDeptData = [
{ deptId: 1, deptName: '总部门', parentId: 0, orderNum: 1 },
{ deptId: 2, deptName: '技术部', parentId: 1, orderNum: 2 },
{ deptId: 3, deptName: '产品部', parentId: 1, orderNum: 1 },
{ deptId: 4, deptName: '前端组', parentId: 2, orderNum: 1 },
];
经过函数处理后,输出的是
[
{
value: 1,
label: '总部门',
parentId: 0,
children: [
{
value: 3,
label: '产品部',
parentId: 1,
children: []
},
{
value: 2,
label: '技术部',
parentId: 1,
children: [
{ value: 4, label: '前端组', parentId: 2, children: [] }
]
}
]
}
]