测试数据:
const list = [
{ id: 1, pid: 0, name: '四川' },
{ id: 2, pid: 1, name: '成都' },
{ id: 3, pid: 1, name: '宜宾' },
{ id: 4, pid: 1, name: '绵阳' },
{ id: 5, pid: 1, name: '德阳' },
{ id: 6, pid: 2, name: '高新区' },
{ id: 7, pid: 2, name: '武侯区' },
{ id: 8, pid: 3, name: '翠屏区' }
];
方法一: 使用递归进行转换. 传入数组,根节点父级id,返回一个树结构的数组.
const arrayToTree = (arr, pid) => {
return arr.reduce((res, current) => {
if (current['pid'] === pid) {
current.children = arrayToTree(arr, current['id']);
return res.concat(current);
}
return res;
}, []);
};
console.log(arrayToTree(list, 0))
方法二:hash表 + 引用关系.传入数组,根节点id ,返回一个树结构对象
const arrayToTree = (arr, rootId) => {
const map = {};
for (const iterator of arr) {
map[iterator['id']] = iterator;
}
for (const iterator of arr) {
const key = iterator['pid'];
if (!(key in map)) continue;
map[key].children = (map[key].children || []).concat(iterator);
}
return map[rootId];
};
console.log(arrayToTree(list, 1));