直接上代码
function toTree(data) {
const dataMap = {};
data.forEach(item => {
dataMap[item.id] = item;
});
const result = [];
data.forEach(item => {
let parent = dataMap[item.pid];
parent?(parent.children || (parent.children = [])).push(item):result.push(item);
});
return result;
}
测试数据
[
{id: 1, pid: 0, label: 'aaaaa'},
{id: 2, pid: 1, label: 'bbbbb'},
{id: 3, pid: 1, label: 'ccccc'},
{id: 4, pid: 0, label: 'ddddd'},
{id: 5, pid: 4, label: 'eeeee'},
{id: 6, pid: 1, label: 'fffff'},
{id: 7, pid: 0, label: 'ggggg'},
{id: 8, pid: 6, label: 'hhhhh'}
]
输出结果
[{
"id": 1,
"pid": 0,
"label": "aaaaa",
"children": [{
"id": 2,
"pid": 1,
"label": "bbbbb"
}, {
"id": 3,
"pid": 1,
"label": "ccccc"
}, {
"id": 6,
"pid": 1,
"label": "fffff",
"children": [{
"id": 8,
"pid": 6,
"label": "hhhhh"
}]
}]
}, {
"id": 4,
"pid": 0,
"label": "ddddd",
"children": [{
"id": 5,
"pid": 4,
"label": "eeeee"
}]
},
{
"id": 7,
"pid": 0,
"label": "ggggg"
}
]
此方法主要使用到了JS对象和引用类型,应该是你想要的吧~