业务需求:后台返回的数据是一个数组,但是客户需要级联的效果,所以必须要处理数据成tree。
源数据结构:
目标数据结构:
处理代码:
export const delDepartTree = (data) => {
const obj = {} // 重新存储数据
const res = [] // 存储最后结果
const len = data.length
const id = 'id'
const parentId = 'parentId'
const children = 'children'
// 遍历原始数据data,构造obj数据,键名为id,值为数据
for (let i = 0; i < len; i++) {
obj[data[i][id]] = data[i]
}
// 遍历原始数据
for (let j = 0; j < len; j++) {
const list = data[j]
// 通过每条数据的 pid 去obj中查询
const parentList = obj[list[parentId]]
if (parentList) {
// 根据 pid 找到的是父节点,list是子节点,
if (!parentList[children]) {
parentList[children] = []
}
// 将子节点插入 父节点的 children 字段中
parentList[children].push(list)
} else {
// pid 找不到对应值,说明是根结点,直接插到根数组中
res.push(list)
}
}
return res
}