有时候后端给我们的接口文档,有的数据是没有帮我们处理过的,所以我们前端要自行处理一些后端未处理的数据,
比如: 树形结构的数据
将数组数据转化成树形结构
// 独立封装树形数据转换方法
export function listToTreeData(list, pid) {
// 1.遍历列表的所有元素
list.forEach(item => {
// 2.顶级部门不管,只找属于别人子部门的元素
if (item.pid !== pid) {
// 3.找到父部门推进去
const parent = list.find(el => el.id === item.pid)
if (parent) {
parent.children = parent.children || []
parent.children.push(item)
}
}
})
// 4.return 在顶级数据当中,要将刚刚被 放入 children 的属于其他部门的子部门过滤掉
return list.filter(item => item.pid === pid)
}
或者 我们需要将列表型的数据,转化成树形数据,用递归算法
/** *
*
* 将列表型的数据转化成树形数据 => 递归算法 => 自身调用自身 => 一定条件不能一样, 否则就会死循环
* 遍历树形 有一个重点 要先找一个头儿
* ***/
export function tranListToTreeData(list, rootValue) {
var arr = []
list.forEach(item => {
if (item.pid === rootValue) {
// 找到之后 就要去找 item 下面有没有子节点
const children = tranListToTreeData(list, item.id)
if (children.length) {
// 如果children的长度大于0 说明找到了子节点
item.children = children
}
arr.push(item) // 将内容加入到数组中
}
})
return arr
}