const list = [{id: 100,name: 100, pid: 10}, {id: 20, name: 20, pid: 2}, {id: 1, name: 1}, {id: 2, name: 2}, {id: 10, name: 10, pid: 1}, {id: 11, name: 11, pid: 1}]
const arrayToTree = (array, pid) => {
return array.reduce((res, current) => {
if (current.pid === pid) {
current.children = arrayToTree(array, current.id)
return res.concat(current)
}
return res;
}, [])
}
console.log('arrayToTree: ', arrayToTree(list))
使用递归将一维数组转换为树型结构
Leave a reply