/*
* @Description:
* @Author: 刘洋
* @Date: 2022-07-14 09:08:32
* @LastEditTime: 2022-07-24 12:48:05
* @LastEditors: xxx
*/
let arr = [
{name: "李四", id: 2, pid: 0},// []
{name: "王五", id: 3, pid: 0}, // [1,2]
{name: "赵六", id: 4, pid: 3}, // []
{name: "吗六", id: 1, pid: 3}, // []
{name: "张三", id: 1, pid: 3}, // []
]
// tree 转 数组
for (let i = 0; i < obj.length; i++) {
console.log(obj[i])
if(obj[i].child){
obj = obj.concat(obj[i].child)
}
}
// 递归
function arrayToTree(arr, pid) {
if (!Array.isArray(arr) || !arr.length) return [];
let res = []
arr.forEach(item => {
if (item.pid === pid) {
let child = arrayToTree(arr, item.id);
if (child.length) item.child = child
res.push(item)
}
})
return res
}
// obj 特性实现
function ArrAyToTreeMap(arr) {
if (!Array.isArray(arr) || !arr.length) return;
let map = {}
arr.forEach(item => map[item.id] = item)
let res = []
arr.forEach(item => {
let mapPid = map[item.pid]
// console.log(mapPid, "mapPid")
if (mapPid) {
((mapPid.child || (mapPid.child = [])).push(item))
} else {
res.push(item)
}
})
return res;
}
console.log(arrayToTree(arr,0))
// console.log(ArrAyToTreeMap(arr))
发表评论