格式转成antd 的Tree控件所需数据类型
返回数据:
const initTree = [
{
id: 1,
name: "Teacher",
parent_id: 0,
full_path: "Teacher",
description: "1",
admin_id: "1",
},
{
id: 2,
name: "Basic",
parent_id: 1,
full_path: "Teacehr/Basic",
description: "1",
admin_id: "1",
},
];
转换Func:
const toTree = (data) => {
if (!data) {
return;
}
let nodes = {};
let parentNodes = {};
data.forEach((node) => {
node['key'] = node.full_path
node['title'] = node.name
let id = node.id;
let parent_id = node.parent_id || 'root';
nodes[id] = node;
if (parent_id) {
parentNodes[parent_id] = parentNodes[parent_id] || [];
parentNodes[parent_id].push(node);
}
});
for (let id in nodes) {
let node = nodes[id];
if (parentNodes[id]) {
node['children'] = parentNodes[id];
} else {
node['leaf'] = true;
}
}
return parentNodes['root'];
}
结果:
image.png
网友评论