将如下结构转成父节点为type,子节点为project,孙子节点为byLaws
[
{
"lineCode": "tj10",
"lineName": "天津10号线",
"type": "培训管理",
"project": "无",
"byLaws": "培训期间,违反培训管理相关规定的。",
"assessCriteria": -200,
"deductionCriteria": 0
},
{
"lineCode": "tj10",
"lineName": "天津10号线",
"type": "任务管理",
"project": "2级",
"byLaws": "未按计划参加安全会或月度培训的。",
"assessCriteria": -1500,
"deductionCriteria": 0
},
{
"lineCode": "tj10",
"lineName": "天津10号线",
"type": "任务管理",
"project": "2级",
"byLaws": "测试度培训的。",
"assessCriteria": -1500,
"deductionCriteria": 0
},
{
"lineCode": "tj10",
"lineName": "天津10号线",
"type": "培训管理",
"project": "中国",
"byLaws": "培训期间,违反培训管理相关规定的。",
"assessCriteria": -200,
"deductionCriteria": 0
}
]
function buildTree(data) {
let nodeId = 1;
const list = [];
const obj = {};
data.forEach(item => {
const type = item.type;
const project = item.project;
const byLaws = item.byLaws
if (!obj[type]) {
obj[type] = { id: nodeId++, label: type, children: [] };
list.push(obj[type]);
}
const projects = obj[type].children;
let projectNode = projects.find(p => p.label === project)
if (!projectNode) {
projectNode = { id: nodeId++, label: project, children: [] };
projects.push(projectNode);
}
projectNode.children.push({ id: nodeId++, label: byLaws });
});
return list;
}