树形结构递归处理函数
// 封装递归方法
export function tranListToTreeDate(list, currentId) {
// 创建一个数组存放结果
const res = []
list.forEach(item => {
if (item.pid === currentId) {
// 递归部分
const children = tranListToTreeDate(list, item.id)
// 如果找到, 就放入当前 children 中
// 否则停止
if (children.length > 0) {
item.children = children
}
res.push(item)
}
})
return res
}
使用说明
list 为扁平数据数组
currentId 为父节点ID pid ===父节点ID 根据自己业务需求修改即可
属性数据扁平处理
/转结构(list就是你要转的树状数据)
treeToList(list) {
let res = []
for (const item of list) {
const { children, ...i } = item
if (children && children.length) {
res = res.concat(this.treeToList(children))
}
res.push(i)
}
return res
}
//查看数据是否转换成功
const treeList = this.treeToList(this.treeData)
console.log('树状结构转扁平结构', treeList)