js實現無限層級樹形數據結構(創新算法) 轉載:https://blog.csdn.net/Mr_JavaScript/article/details/82817177 因爲作項目的須要,把一個線性數組轉成樹形數組,在網上查了不少文章,以爲他們寫的太複雜了,因而本身寫了一個,在折騰了一下午終於把它寫出來啦(激動.gif),用兩個filter過濾器就搞定了,代碼簡潔明瞭,數據結構小白都能看懂。 js代碼:把線性數據轉成樹形數據 function setTreeData(data){ let cloneData = JSON.parse(JSON.stringify(data)) // 對源數據深度克隆 let tree = cloneData.filter((father)=>{ //循環全部項 let branchArr = cloneData.filter((child)=>{ return father.id == child.parentId //返回每一項的子級數組 }); if(branchArr.length>0){ father.children = branchArr; //若是存在子級,則給父級添加一個children屬性,並賦值 } return father.parentId==0; //返回第一層 }); return tree //返回樹形數據 } 根據網友給我指出的問題,以前的算法會影響到源數據,以後我對獲取的數據進行了深度克隆,完美解決。 實例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)) // 對源數據深度克隆 let tree = cloneData.filter((father)=>{ //循環全部項 let branchArr = cloneData.filter((child)=>{ return father.id == child.parentId //返回每一項的子級數組 }); if(branchArr.length>0){ father.children = branchArr; //若是存在子級,則給父級添加一個children屬性,並賦值 } return father.parentId==0; //返回第一層 }); return tree //返回樹形數據 } }, methods:{ handleNodeClick(data){ // console.log(data) console.log(this.treeData) } }, mounted(){ } } </script> <style scoped> </style>
顯示效果:vue