需求:有组织部门信息,组成层级结构作为树形控件的数据
数据结构(已脱敏处理)
代码如下
// 原始数据
deptList: [],
// 待构建树形结构数据
deptTree: [],
// pid初始父节点值
initTree (pid) {
// filter自定义方法过滤符合子树的集合
const child = this.deptList.filter(item => item.parentcode === pid)
return child.map(item => {
if (this.initTree(item.deptcode).length > 0) {
return {
...item,
childrens: this.initTree(item.deptcode)
}
} else {
return item
}
})
}
// 调用
this.deptTree = this.initTree('')
initTree还可以任意指定,获取树上某节点以下全部子结构