码迷,mamicode.com
首页 > Web开发 > 详细

简单json---转树形json

时间:2019-04-03 12:27:33      阅读:537      评论:0      收藏:0      [点我收藏+]

标签:com   folder   sig   calendar   应用   技术   foreach   防止   glob   

var data = [    
     {"fileName":"navone","layFilterId":"layadmin-system-side-menu"}
    ,{"pId":0,"id":1,"icon":"fa fa-globe","nodeName":"所有商品"}
    ,{"pId":0,"id":2,"icon":"fa fa-flash","nodeName":"页面"}
    ,{"pId":0,"id":3,"icon":"fa fa-database","nodeName":"应用"}
    ,{"pId":0,"id":4,"icon":"icomoon icon-signal-tower","nodeName":"管理","lay-href":"https://www.amap.com/"}
    ,{"pId":0,"id":5,"icon":"icomoon icon-camera","nodeName":"模块"}
    ,{"pId":0,"id":6,"icon":"fa fa-globe","nodeName":"授权"}
    
    ,{"pId":1,"id":11,"icon":"fa fa-calendar","nodeName":"设置","lay-href":"http://map.baidu.com"}
    ,{"pId":1,"id":12,"icon":"fa fa-folder-o","nodeName":"监控"}
    ,{"pId":1,"id":13,"icon":"fa fa-map","nodeName":"杆塔"}
    ,{"pId":2,"id":21,"icon":"fa fa-globe","nodeName":"第三极"}
    
    ,{"pId":21,"id":211,"icon":"fa fa-file-text","nodeName":"远程杆塔"}
]
var indexPage = {}; 

//将简单json转为父子关系json
  indexPage.fatherSubTree = function(jsonData) {
      // 删除 所有 children,以防止多次调用
      jsonData.forEach(function (item) {
          delete item.children;
      });
            
      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {};
      jsonData.forEach(function (item) {
            map[item.id] = item;
       });
                    
       var val = [];
       jsonData.forEach(function (item) {
            // 根据pid找到map中指定的父类
            var parent = map[item.pId];
            
            // 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
            if (parent) {
                (parent.children || ( parent.children = [] )).push(item);
            } else {
              //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
                 val.push(item);
            }
                        
    });
  return val;
}

技术图片

 

简单json---转树形json

标签:com   folder   sig   calendar   应用   技术   foreach   防止   glob   

原文地址:https://www.cnblogs.com/littleboyck/p/10647739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!