现在要求实现一个方法,把原始树形结构的数据转换成数组,数组格式如:id 代表部门编号,name 是部门名称,parentId 是父部门编号,为 0 代表一级部门;原数数据结构如下:
// 原始数据
let result = [
{
name: '部门A',
children: [
{
name: '部门B',
children: [
{
name: '部门C',
children: []
},
{
name: '部门D',
children: []
}
]
},
{
name: '部门E',
children: [
{
name: '部门F',
children: []
}
]
}
]
}
];
// 转换后的结果如下
let data =[
{id:1,name:'部门A',parentId:0},
{id:2,name:'部门B',parentId:1},
{id:3,name:'部门C',parentId:2},
{id:4,name:'部门D',parentId:2},
{id:5,name:'部门E',parentId:1},
{id:6,name:'部门F',parentId:5},
];
代码如下
function flattenTree(tree) {
let result = [];
function traverse(node, parentId) {
const nodeId = result.length + 1;
const obj = {...node, id: nodeId, parentId }
delete obj.children
result.push(obj);
if (node.children && node.children.length > 0) {
node.children.forEach(child => {
traverse(child, nodeId);
});
}
}
tree.forEach(node => {
traverse(node, 0);
});
return result;
}