当前位置:首页 >> 网络编程

js实现无限层级树形数据结构(创新算法)

由于做项目的需要,把一个线性数组转成树形数组,在网上查了很多文章,觉得他们写的太复杂了,于是自己写了一个,在折腾了一下午终于把它写出来啦(激动.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 "htmlcode">
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 "text-align: center">js实现无限层级树形数据结构(创新算法)

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 "_blank" href="https://github.com/KBeginner/Coder/blob/v2018/JavaScript/js%E6%A0%91%E5%BD%A2%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/Test.html" rel="external nofollow" >Demo

树形数据转成扁平数据,请查看这篇文章:js实现树形数据转成扁平数据