zoukankan      html  css  js  c++  java
  • js数组和树互转

    1. 数组转树

    const arr = [
        {id:1, parentId: null, name: 'a'},
        {id:2, parentId: null, name: 'b'},
        {id:3, parentId: 1, name: 'c'},
        {id:4, parentId: 2, name: 'd'},
        {id:5, parentId: 1, name: 'e'},
        {id:6, parentId: 3, name: 'f'},
        {id:7, parentId: 4, name: 'g'},
        {id:8, parentId: 7, name: 'h'},
    ]

    1.1 利用map存储数组项,空间换时间

    function array2Tree(arr){
        if(!Array.isArray(arr) || !arr.length) return;
        let map = {};
        arr.forEach(item => map[item.id] = item);
    
        let roots = [];
        arr.forEach(item => {
            const parent = map[item.parentId];
            if(parent){
                (parent.children || (parent.children=[])).push(item);
            }
            else{
                roots.push(item);
            }
        })
    
        return roots;
    }

    1.2 利用递归

    //需要插入父节点id,pid为null或'',就是找root节点,然后root节点再去找自己的子节点
    function array2Tree(data, pid){
        let res = [];
        data.forEach(item => {
            if(item.parentId === pid){
                let itemChildren = array2Tree(data,item.id);
                if(itemChildren.length) item.children = itemChildren;
                res.push(item);
            }
        });
        return res;
    }  

    2. 树转数组

    2.1 深度优先遍历

    function dfs(root,fVisit){
        let stack = Array.isArray(root) ? [...root] : [root];
        while(stack.length){
            let node = stack.pop();
            fVisit && fVisit(node);
            let children = node.children;
            if(children && children.length){
                for(let i=children.length-1;i>=0;i--) stack.push(children[i]);
            }
        }
    }

    2.2 广度优先遍历

    function bfs(root,fVisit){
        let queue = Array.isArray(root) ? [...root] : [root];
        while(queue.length){
            let node = queue.shift();
            fVisit && fVisit(node);
            let children = node.children;
            if(children && children.length){
                for(let i=0;i<children.length;i++) queue.push(children[i]);
            }
        }
    }

    3. 验证

    //验证数组转树
    let a = array2Tree(arr,null);
    console.log(a);
    
    //验证树转数组
    let a1 = [];
    bfs(a,node => a1.push(node));
    console.log(a1);
  • 相关阅读:
    selenium 设置等待时间
    mac下配置python+selenium+chrome环境
    自定义filter
    urllib登录的cookie复制到headers,模拟登录人人网
    urllib中的保存cookie使用,运用cookiejar来模拟登录人人网
    urllib中的cookie使用,四种方法
    urllib中的https使用,导入ssl模块
    urllib判断重定向
    urllib中的down,下载百度图片为例
    urllib中的本地代理设置
  • 原文地址:https://www.cnblogs.com/mengff/p/13142128.html
Copyright © 2011-2022 走看看