用递归算法实现
var arr = [
{ id: '29', pid: '', name: '总裁办' },
{ id: '2c', pid: '', name: '财务部' },
{ id: '2d', pid: '2c', name: '财务核算部' },
{ id: 'd2', pid: '', name: '技术部' },
{ id: 'd3', pid: 'd2', name: 'Java研发部' }
]
export function Doto(arr, pid = '') {
//定义一个空数组
const newArr = []
//循环遍历arr数组
arr.forEach(element => {
if (element.pid === pid) {
const child = Doto(arr, element.id)
if (child.length) {
element.children = child
}
//将遍历出来的每一项加入新数组
newArr.push(element)
}
})
//返回
return newArr
}
console.dir(Doto(arr))
第二种通过第三方包来实现
第一步下载第三方包
$ npm install array-to-tree --save 或者 yarn add array-to-tree
第二步导入
import arrayToTree from 'array-to-tree'
export function Doto2(arr) {
return arrayToTree(arr, {
parentProperty: 'pid',
customID: 'id'
})
}