前言:公司后台返回来的数据是一个树形数据结构,关键是还要用element-ui中el-tree组件渲染成树形结构,一上来给俺整蒙了。研究了一波element-ui中树形组件的传值的实现和后台返回来的数据,加上网上搜索树形数据结构的处理思想,有了以下成果。
<script>
// pid表示当前对象的父节点对象的id值
const list = [
{ id: 1, pid: 0 },
{ id: 2, pid: 1 },
{ id: 3, pid: 2 },
{ id: 4, pid: 2 },
{ id: 5, pid: 4 },
{ id: 6, pid: 0 }
]
// 处理树形数据结构主要是利用递归思想
function treeData(arr,pid){
return res =arr.filter((item)=>{
if(item.pid===pid){
// 给当前找到的符合的对象添加一个chnildren属性来找到子对象对象的数据
item.children=this.treeData(arr,item.id)
return true
}
})
}
console.log(treeData(list,0));
</script>
执行结果