记录 第二天
js的树形结构介绍
let treeData = [
{
//展示的名字
text:'team1',
//专属的值
value:'1',
//树的子集
children:[
{
text:'team1-1',
value:'1-1',
children:[]
},{
text:'team1-2',
value:'1-2',
children:[]
}
]
},
{
text:'team2',
value:'2',
children:[
{
text:'team2-1',
value:'2-1',
children:[]
}
]
}
]
通常接口返回的数据是这样的格式
当我们只知道当前节点value的时候怎么去获取全路径
1.递归查找
声明一个类,创建查找方法,最后使用fatherPath方法用一个变量去接收值
let find = new Find(treeData,value)
//返回的是index的路径 如 [1,1] 则是 treeData[1].children[1]
let path = find.fatherPath()
class Find{
constructor(data,value){
this.data = data
this.value = value
//存储路径
this.path = []
//找寻状态
this.findState = false
}
findFather(data,value){
data.forEach((item,index)=>{
//如果找到了直接返回
if(this.findState) return
//在遍历过程中保存路径
this.path.push(index)
//如果找到了改变状态
if(item.value == this.value){
this.findState = true
}else if(item.children.length >0){
//还未找到并且有子集重新调用方法
this.findFather(item.children,value)
}else{
//清除缓存
this.path.pop()
}
})
}
//找爸爸的path
fatherPath(){
this.findFather(this.data,this.value)
return this.path
}
}
2.处理后台返回数据
我们接收数据可能会用到很多的ui组件去做树的展示 当我们的ui组件获取不到path或者level的时候会对点击数据时的处理不太友好
//treeData树节点 level上级层级 path上级路径
function addName(treeData,level,path){
//如果传进来的参数不是数组返回false
if(!Array.isArray(treeData))return
return treeData.filter((item,index)=>{
//给每一级添加level
item['level']=level?level++:1
//给每一级添加路径
item['path']= path?path + ',' + index:index.toString()
if(item.children.length !== 0) return addName(item.children,item.level,item.path)
})
}
//调用方法
addName(treeData)
结语
其实还有很多其他的方法可以实现,根据需求尽量精简代码,分享一个我的思路, 假设我们只需要知道这个子级value的第一级目录,我们只需要保存第一级路径如果找到了改变状态终止循环返回数据。