zoukankan      html  css  js  c++  java
  • js 数组转树型结构数据

    let 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}
    ];
    /**
     * 数组转树  非递归求解
     * 利用数组和对象相互引用  时间复杂度O(n)
     * @param {Object} list
     */
    function 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;
    }
    
    let res1 = totree(arr,0)
    
    /**
     * 数组转树  递归求解
     */
    function toTree(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)
    }
    
    let result = toTree(arr,0)
  • 相关阅读:
    项目开发基础概念
    django 对接elasticsearch实现全文检索
    win10安装docker
    Mac VMware Fusion 中修改 centos7 虚拟机的磁盘空间、扩容
    CentOS 7下 YUM 本地仓库的搭建
    mac与虚拟机传输文件
    mac和windows快速锁定电脑
    rpm -qa详解
    虚拟机安装centos6
    mac与iPhone互传文件
  • 原文地址:https://www.cnblogs.com/Sabo-dudu/p/15166296.html
Copyright © 2011-2022 走看看