05 - json转成树状结构

Posted 司空大大

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了05 - json转成树状结构相关的知识,希望对你有一定的参考价值。

 1 /** 
 2  * json格式转树状结构 
 3  * @param   {json}      json数据 
 4  * @param   {String}    id的字符串 
 5  * @param   {String}    父id的字符串 
 6  * @param   {String}    children的字符串 
 7  * @return  {Array}     数组 
 8  */  
 9 function transData(a, idStr, pidStr, chindrenStr){  
10     var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;  
11     for(; i < len; i++){  
12         hash[a[i][id]] = a[i];  
13     }  
14     for(; j < len; j++){  
15         var aVal = a[j], hashVP = hash[aVal[pid]];  
16         if(hashVP){  
17             !hashVP[children] && (hashVP[children] = []);  
18             hashVP[children].push(aVal);  
19         }else{  
20             r.push(aVal);  
21         }  
22     }  
23     return r;  
24 }  
25   
26 var jsonData = eval(‘[
27     {"id":"4","pid":"1","name":"大家电"},
28     {"id":"5","pid":"1","name":"生活电器"},
29     {"id":"1","pid":"0","name":"家用电器"},
30     {"id":"2","pid":"0","name":"服饰"},
31     {"id":"3","pid":"0","name":"化妆"},
32     {"id":"7","pid":"4","name":"空调"},
33     {"id":"8","pid":"4","name":"冰箱"},
34     {"id":"9","pid":"4","name":"洗衣机"},
35     {"id":"10","pid":"4","name":"热水器"},
36     {"id":"11","pid":"3","name":"面部护理"},
37     {"id":"12","pid":"3","name":"口腔护理"},
38     {"id":"13","pid":"2","name":"男装"},
39     {"id":"14","pid":"2","name":"女装"},
40     {"id":"15","pid":"7","name":"海尔空调"},
41     {"id":"16","pid":"7","name":"美的空调"},
42     {"id":"19","pid":"5","name":"加湿器"},
43     {"id":"20","pid":"5","name":"电熨斗"}
44     ]‘);  
45   
46 var jsonDataTree = transData(jsonData, ‘id‘, ‘pid‘, ‘chindren‘);  
47 console.log(jsonDataTree);  
48 //结果如下:
49 [
50     {"id":"1","pid":"0","name":"家用电器", "chindren":[
51         {"id":"4","pid":"1","name":"大家电", "chindren":[
52             {"id":"7","pid":"4","name":"空调", "chindren":[
53                 {"id":"15","pid":"7","name":"海尔空调"},
54                 {"id":"16","pid":"7","name":"美的空调"}
55             ]},
56             {"id":"8","pid":"4","name":"冰箱"},
57             {"id":"9","pid":"4","name":"洗衣机"},
58             {"id":"10","pid":"4","name":"热水器"}
59         ]},
60         {"id":"5","pid":"1","name":"生活电器","chindren":[
61             {"id":"19","pid":"5","name":"加湿器"},
62             {"id":"20","pid":"5","name":"电熨斗"}
63         ]}
64     ]},
65     {"id":"2","pid":"0","name":"服饰","chindren":[
66         {"id":"13","pid":"2","name":"男装"},
67         {"id":"14","pid":"2","name":"女装"}
68     ]},
69     {"id":"3","pid":"0","name":"化妆","chindren":[
70         {"id":"11","pid":"3","name":"面部护理"},
71         {"id":"12","pid":"3","name":"口腔护理"}
72     ]}
73 ]  

 

以上是关于05 - json转成树状结构的主要内容,如果未能解决你的问题,请参考以下文章

将扁平的分层数据转换为树状结构的 JSON

json转树状结构

树状结构的json

从大型 JSON 文件创建树状结构的最有效方法

将组织结构转换为树状json

cJson 常见用法