格式轉(zhuǎn)成antd 的Tree控件所需數(shù)據(jù)類型
返回數(shù)據(jù):
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",
},
];
轉(zhuǎn)換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'];
}
結(jié)果: