项目中后台传过来的节点数据如下:
let data = [
{
id: '1',
name: 'A',
parentId: '-1'
}, {
id: '2',
name: 'B',
parentId: '-1'
}, {
id: '3',
name: 'C',
parentId: '1'
}, {
id: '4',
name: 'D',
parentId: '1'
}, {
id: '15',
name: 'E',
parentId: '2'
}, {
id: '6',
name: 'F',
parentId: '4'
}, {
id: '7',
name: 'G',
parentId: '3'
}, {
id: '8',
name: 'H',
parentId: '6'
}
];
现在要将他转换成element tree的结构:
let tree = [];
let o = {};
initDataStruct();
parse(o, tree);
console.log(tree);
function initDataStruct() {
data.forEach((v) => {
v.children = [];
})
data.forEach((v, i) => {
o[v.parentId] = [];
});
data.forEach((v, i) => {
o[v.parentId].push(v);
});
// 添加根节点
tree = o['-1'];
}
function parse(o, tree) {
for(let i = 0; i < tree.length; i++) {
for(attr in o) {
if(tree[i].id === o[attr][0].parentId) {
tree[i].children = o[attr];
}
}
parse(o, tree[i].children);
}
}
ok,转换成功!