数组转成树需要数据,套用到el-tree

33 篇文章 1 订阅
21 篇文章 1 订阅

今天,突发奇想之前,树结构数据都是后台编好了传给我,今天想了一下自己做一数组,然后做一树,

<template>
  <div>
    <el-tree 
      :data="data" 
      :props="defaultProps" 
      @node-click="handleNodeClick"
      :default-expand-all="true"
      :expand-on-click-node="true"
      :auto-expand-parent="false"
    ></el-tree>
  </div>
</template>
<script>
  export default {
    name: 'edit',
    props: {},
    data() {
      return {
        arr:[
          {id:2,name:'部门1',parentId:0},
          {id:3,name:'部门2',parentId:1},
          {id:1,name:'部门3',parentId:2},
          {id:4,name:'部门4',parentId:1},
          {id:5,name:'部门5',parentId:2},
          {id:6,name:'部门6',parentId:3},
          {id:7,name:'部门7',parentId:2},
          {id:8,name:'部门8',parentId:4},
          {id:9,name:'部门9',parentId:5},
          {id:10,name:'部门10',parentId:0},
          {id:11,name:'部门11',parentId:10},
        ],
        data: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      }
    },
    created() {
      this.urlFunction(this.arr,0)
    },
    methods: {
      urlFunction(list,parId){
        var tree = this.totree(list,parId);
        this.data = tree;
        console.log(tree);
        var newTree = this.newToTree(list,parId);
        console.log(newTree);
      },
      //  数组转树  非递归求解
      //  利用数组和对象相互引用  时间复杂度O(n)
      //  @param {Object} list
      totree(list,parId) {
        let obj = {};
        let result = [];
        //将数组中数据转为键值对结构 (这里的数组和obj会相互引用)
        list.map(el => {
          obj[el.id] = el;
        })
        for(let i=0, len = list.length; i < len; i++) {
          let id = list[i].parentId;
          if(id == parId) {
            result.push(list[i]);
            continue;
          }
          if(obj[id].children) {
            obj[id].children.push(list[i]);
          } else {
            obj[id].children = [list[i]];
          }
        }
        return result;
      },
      //数组转树  递归求解
      newToTree(list,parId){
        let len = list.length
        function loop(parId){
          let res = [];
          for(let i = 0; i < len; i++){
            let item = list[i]
            if(item.parentId === parId){
              item.children = loop(item.id)
              res.push(item)
            }
          }
          return res
        }
        return loop(parId)
      }
    }
  }
</script>


转载:https://www.cnblogs.com/Sabo-dudu/p/15166296.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值