简单json---转树形json
Posted littleboyck
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单json---转树形json相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
Javascript中扁平化数据结构与JSON树形结构转换详解