接口返回格式:
let pathList = [
{isFolder: true, pathRel: "/文件夹", path: "D:/IndexRoot/abc/文件夹"},
{isFolder: true, pathRel: "/文件夹2", path: "D:/IndexRoot/abc/文件夹2"},
]
转为 antd 文件目录的数据格式
//['文件夹', 'a.txt']
function add_item(p: string[], is_f: boolean, add_p: string[]) {
if (p.length === 0) {
return [];
}
let is_folder = true;
if (p.length === 1) {
is_folder = is_f;
}
let first_item = p.shift() || '';
add_p.push(first_item);
let temp: DataNode[] = [{
title: first_item,
key: add_p.join('/'),
isLeaf: !is_folder,
children: add_item(p, is_f, add_p),
}];
return temp;
}
// 同title的合并
function merge_item(nodes: DataNode[]) {
if (nodes.length <= 0) {
return [];
}
let children: DataNode[] = [];
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let index = findIndex(children, ['title', node.title]);
if (index > -1) {
children[index].children = children[index].children?.concat(node.children || [])
} else {
children.push({
title: node.title,
key: node.key,
isLeaf: node.isLeaf,
children: node.children,
})
}
}
for (let c = 0; c < children.length; c++) {
children[c].children = merge_item(children[c].children || [])
}
return children
}
let node_list: DataNode[] = []
for (let i = 0; i < pathList.length; i++) {
let o = resFol.data.pathList[i];
let names = o.pathRel.split('/');
names.shift();
let one = add_item(names, o.isFolder, [o.path.replace(o.pathRel, '')])[0];
node_list = node_list.concat(one)
}
let all = merge_item(node_list);
上面的 all 就是antd 的格式了,类似如下:
const treeData: DataNode[] = [
{
title: 'parent 0',
key: '0-0',
children: [
{ title: 'leaf 0-0', key: '0-0-0', isLeaf: true },
{ title: 'leaf 0-1', key: '0-0-1', isLeaf: true },
],
},
{
title: 'parent 1',
key: '0-1',
children: [
{ title: 'leaf 1-0', key: '0-1-0', isLeaf: false },
{ title: 'leaf 1-1', key: '0-1-1', isLeaf: true },
],
},
];
最终的样子: