js 无限层级树形数据结构 js实现无限层级树形数据结构(创新算法)
蔚莱先森 人气:1由于做项目的需要,把一个线性数组转成树形数组,在网上查了很多文章,觉得他们写的太复杂了,于是自己写了一个,在折腾了一下午终于把它写出来啦(激动.gif),用两个filter过滤器就搞定了,代码简洁明了,数据结构小白都能看懂。
js代码:把扁平数据转成树形数据
function setTreeData(source){ let cloneData = JSON.parse(JSON.stringify(source)) // 对源数据深度克隆 return cloneData.filter(father=>{ // 循环所有项,并添加children属性 let branchArr = cloneData.filter(child=> father.id == child.parentId); // 返回每一项的子级数组 branchArr.length>0 ? father.children=branchArr : '' //给父级添加一个children属性,并赋值 return father.parentId==0; //返回第一层 }); }
根据网友给我指出的问题,之前的算法会影响到源数据,之后我对获取的数据进行了深度克隆,完美解决。
封装函数:
function treeData(source, id, parentId, children){ let cloneData = JSON.parse(JSON.stringify(source)) return cloneData.filter(father=>{ let branchArr = cloneData.filter(child => father[id] == child[parentId]); branchArr.length>0 ? father[children] = branchArr : '' return father[parentId] == 0 // 如果第一层不是parentId=0,请自行修改 }) } // 调用时,字段名以字符串的形式传参,如treeData(source, 'id', 'parentId', 'children')
实例1:使用element-ui的组件制作一个树形多级嵌套伸缩菜单栏
实现效果:
vue组件:
<template> <el-tree :data="treeData" :props="defaultProps" accordion @node-click="handleNodeClick"> </el-tree> </template> <script> export default { name: "Test", data(){ return { data : [ {id:1,parentId:0,name:"一级菜单A",rank:1}, {id:2,parentId:0,name:"一级菜单B",rank:1}, {id:3,parentId:0,name:"一级菜单C",rank:1}, {id:4,parentId:1,name:"二级菜单A-A",rank:2}, {id:5,parentId:1,name:"二级菜单A-B",rank:2}, {id:6,parentId:2,name:"二级菜单B-A",rank:2}, {id:7,parentId:4,name:"三级菜单A-A-A",rank:3}, {id:8,parentId:7,name:"四级菜单A-A-A-A",rank:4}, {id:9,parentId:8,name:"五级菜单A-A-A-A-A",rank:5}, {id:10,parentId:9,name:"六级菜单A-A-A-A-A-A",rank:6}, {id:11,parentId:10,name:"七级菜单A-A-A-A-A-A-A",rank:7}, {id:12,parentId:11,name:"八级菜单A-A-A-A-A-A-A-A",rank:8}, {id:13,parentId:12,name:"九级菜单A-A-A-A-A-A-A-A-A",rank:9}, {id:14,parentId:13,name:"十级菜单A-A-A-A-A-A-A-A-A-A",rank:10}, ], defaultProps: { children: 'children', label: 'name' } } }, computed:{ treeData(){ let cloneData = JSON.parse(JSON.stringify(this.data)) // 对源数据深度克隆 return cloneData.filter(father=>{ let branchArr = cloneData.filter(child=>father.id == child.parentId) //返回每一项的子级数组 branchArr.length>0 ? father.children = branchArr : '' //如果存在子级,则给父级添加一个children属性,并赋值 return father.parentId==0; //返回第一层 }); } }, methods:{ handleNodeClick(data){ // console.log(data) console.log(this.treeData) } }, mounted(){ } } </script> <style scoped> </style>
树形数据转成扁平数据,请查看这篇文章:js实现树形数据转成扁平数据
加载全部内容