数组转树
var b=[{text:'wellintech',state:'open',id:'1'},
{text:'tell',state:'open',id:'2'},
{text:'sfsdf',state:'open',id:'3'},
{text:'dev',state:'open',id:'1/1'},
{text:'web',state:'open',id:'1/2'},
{text:'sdf',state:'open',id:'1/1/1'},
{text:'saf',state:'open',id:'1/2/1'},
{text:'fsasdf',state:'open',id:'2/1'},
{text:'adsf',state:'open',id:'2/2'}
]
function translateDataToTree(data) {
//没有父节点的数据
let parents = data.filter(value => value.id.split('/').length == 1)
//有父节点的数据
let childrens = data.filter(value =>value.id.split('/').length >1)
//定义转换方法的具体实现
let translator = (parents, childrens) => {
//遍历父节点数据
parents.forEach((parent) => {
//遍历子节点数据
childrens.forEach((current, index) => {
//此时找到父节点对应的一个子节点
if (current.id.split('/').slice(0,-1).join('/') === parent.id) {
//对子节点数据进行深复制,这里只支持部分类型的数据深复制,对深复制不了解的童靴可以先去了解下深复制
let temp = JSON.parse(JSON.stringify(childrens))
//让当前子节点从temp中移除,temp作为新的子节点数据,这里是为了让递归时,子节点的遍历次数更少,如果父子关系的层级越多,越有利
temp.splice(index, 1)
//让当前子节点作为唯一的父节点,去递归查找其对应的子节点
translator([current], temp)
//把找到子节点放入父节点的childrens属性中
typeof parent.childrens !== 'undefined' ? parent.childrens.push(current) : parent.childrens = [current]
}
}
)
}
)
}
//调用转换方法
translator(parents, childrens)
//返回最终的结果
return parents
}
var c=translateDataToTree(b);
另一种方法
var b=[{text:'wellintech',state:'open',id:'1'},
{text:'tell',state:'open',id:'2'},
{text:'sfsdf',state:'open',id:'3'},
{text:'dev',state:'open',id:'1/1'},
{text:'web',state:'open',id:'1/2'},
{text:'sdf',state:'open',id:'1/1/1'},
{text:'saf',state:'open',id:'1/2/1'},
{text:'fsasdf',state:'open',id:'2/1'},
{text:'adsf',state:'open',id:'2/2'}
]
function toTree(list){
list.forEach((item,index)=>{
if(item.id.split('/').length>1){
for(let i=0;i<list.length;i++){
if(item.id.split('/').slice(0,-1).join('/')==list[i].id)
{
if(list[i].children)
{
list[i].children.push(item);
}
else
{
list[i].children=[item];
}
break
}
}
}
})
var ls=list.filter((i)=>{if(i.id.split('/').length==1) return true})
return ls
}
var bb=toTree(b)