zoukankan      html  css  js  c++  java
  • pId的数据结构转children 数据结构(JS)

    在工作中经常遇到需要把带有pId的的list数据转换为children格式的树形结构,一直都
    没有找到太好的工具函数。偶然间看到了这个函数,研究了下,感觉这个函数很强大,所以
    记录下来,作为备用,同时也贴出来,供大家使用;
    
    /** 
     * json格式转树状结构 
     * @param   {json}      json数据 
     * @param   {String}    id的字符串 
     * @param   {String}    父id的字符串 
     * @param   {String}    children的字符串 
     * @return  {Array}     数组 
     */  
    function transData(a, idStr, pidStr, chindrenStr){  
        var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;  
        for(; i < len; i++){  
            hash[a[i][id]] = a[i];  
        }  
        for(; j < len; j++){  
            var aVal = a[j], hashVP = hash[aVal[pid]];  
            if(hashVP){  
                !hashVP[children] && (hashVP[children] = []);  
                hashVP[children].push(aVal);  
            }else{  
                r.push(aVal);  
            }  
        }  
        return r;  
    }  
      
    var jsonData = eval('[{"id":"4","pid":"1","name":"大家电"},{"id":"5","pid":"1","name":"生活电器"},{"id":"1","pid":"0","name":"家用电器"},{"id":"2","pid":"0","name":"服饰"},{"id":"3","pid":"0","name":"化妆"},{"id":"7","pid":"4","name":"空调"},{"id":"8","pid":"4","name":"冰箱"},{"id":"9","pid":"4","name":"洗衣机"},{"id":"10","pid":"4","name":"热水器"},{"id":"11","pid":"3","name":"面部护理"},{"id":"12","pid":"3","name":"口腔护理"},{"id":"13","pid":"2","name":"男装"},{"id":"14","pid":"2","name":"女装"},{"id":"15","pid":"7","name":"海尔空调"},{"id":"16","pid":"7","name":"美的空调"},{"id":"19","pid":"5","name":"加湿器"},{"id":"20","pid":"5","name":"电熨斗"}]');  
      
    var jsonDataTree = transData(jsonData, 'id', 'pid', 'chindren');  
    console.log(jsonDataTree);  
    //[{"id":"1","pid":"0","name":"家用电器","chindren":[{"id":"4","pid":"1","name":"大家电","chindren":[{"id":"7","pid":"4","name":"空调","chindren":[{"id":"15","pid":"7","name":"海尔空调"},{"id":"16","pid":"7","name":"美的空调"}]},{"id":"8","pid":"4","name":"冰箱"},{"id":"9","pid":"4","name":"洗衣机"},{"id":"10","pid":"4","name":"热水器"}]},{"id":"5","pid":"1","name":"生活电器","chindren":[{"id":"19","pid":"5","name":"加湿器"},{"id":"20","pid":"5","name":"电熨斗"}]}]},{"id":"2","pid":"0","name":"服饰","chindren":[{"id":"13","pid":"2","name":"男装"},{"id":"14","pid":"2","name":"女装"}]},{"id":"3","pid":"0","name":"化妆","chindren":[{"id":"11","pid":"3","name":"面部护理"},{"id":"12","pid":"3","name":"口腔护理"}]}]
  • 相关阅读:
    【Mysql】可视化工具
    【Mysql】Mysql 各个版本区别
    【Linux】rpm常用命令及rpm参数介绍
    【Mysql】mysql和mariadb的区别
    【CentOS】设置服务开机自动启动
    【Linux】查看所使用的Linux系统是32位还是64 位的方法
    【Linux】安装openssh-server依赖openssh-client版本错误的解决办法
    【Linux】apt-get 源地址汇总
    【Linux】编辑文件时,箭头按键还有BACKSPACE按键不能正常使用的解决办法
    VMware设置桥接上网
  • 原文地址:https://www.cnblogs.com/AlexanderZhao/p/12878897.html
Copyright © 2011-2022 走看看