js生成树结构
1、假树,利用共享内存实现,非真遍历,这个是一种比较直观的写法
let list = [
{id:1,name:100},
{id:11,name:101,pid:1},
{id:111,name:1011,pid:11},
{id:2,name:200},
{id:22,name:202,pid:2},
{id:3,name:3002},
{id:32,name:3003,pid:1},
{id:42,name:4003,pid:111}
]
let mapList = list.reduce((prev,v)=>{
prev[v.id]=v
return prev
},[])
let tree = list.reduce((prev,v)=>{
if(!mapList[v.pid]){
v.children?'':(v.children=[])
prev=[...prev,...[v]]
}else{
mapList[v.pid].children?'':(()=>mapList[v.pid].children=[])()
mapList[v.pid].children=[...mapList[v.pid].children,...[v]]
}
return prev
},[])
console.log(mapList);
console.log(tree);
2.假树, 同第一种原理,非直观写法,是不是简便多了
let tree = list.map(v=>{
v.children?'':(()=>v.children=[])()
v.pid?'':(()=> v.type='parent')()
v.children = list.filter(m=>m.pid===v.id)
return v
}).filter(v=>v.type==='parent')
console.log(list);
console.log(tree);
级联数据拉平
//级联数据拉平
function flatArray(key,deep,arr){
const readNodes = function(key,deep,arr,data=[]){
for (let item of arr) {
data.push(item)
if (item[deep] && item[deep].length){
readNodes(key,deep,item[deep],data)
}
}
return data
}
return readNodes(key,deep,arr)
}
flatArray('id','children',list)
返回父子链
function findParent(value,key,parent,deep,arr1=[]){
let readNodes = (value,key,parent,deep,arr,data=[])=>{
for(let v of arr){
if(!value) break
if(v[key]===value){
data.unshift(v)
readNodes(v[parent],key,parent,deep,arr1,data)
break
}else{
v[deep]&&v[deep].length?readNodes(value,key,parent,deep,v[deep],data):''
}
}
return data
}
return readNodes(value,key,parent,deep,arr1)
}
console.log(findParent(111,'id','pid','children',tree));
作者:沧桑岁月歌
链接:https://www.jianshu.com/p/59a941b5bd8e
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。