码迷,mamicode.com
首页 > 编程语言 > 详细

javascript算法小结

时间:2014-12-24 13:08:22      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

1.扁平结构压成树形结构

http://stackoverflow.com/questions/12831746/javascript-building-a-hierarchical-tree

技术分享
 1 var items = [
 2     {"Id": "1", "Name": "abc", "Parent": "2"},
 3     {"Id": "2", "Name": "abc", "Parent": ""},
 4     {"Id": "3", "Name": "abc", "Parent": "5"},
 5     {"Id": "4", "Name": "abc", "Parent": "2"},
 6     {"Id": "5", "Name": "abc", "Parent": ""},
 7     {"Id": "6", "Name": "abc", "Parent": "2"},
 8     {"Id": "7", "Name": "abc", "Parent": "6"},
 9     {"Id": "8", "Name": "abc", "Parent": "6"}
10 ];
11 
12 function buildHierarchy(arry) {
13 
14     var roots = [], children = {};
15 
16     // find the top level nodes and hash the children based on parent
17     for (var i = 0, len = arry.length; i < len; ++i) {
18         var item = arry[i],
19             p = item.Parent,
20             target = !p ? roots : (children[p] || (children[p] = []));
21 
22         target.push({ value: item });
23     }
24 
25     // function to recursively build the tree
26     var findChildren = function(parent) {
27         if (children[parent.value.Id]) {
28             parent.children = children[parent.value.Id];
29             for (var i = 0, len = parent.children.length; i < len; ++i) {
30                 findChildren(parent.children[i]);
31             }
32         }
33     };
34 
35     // enumerate through to handle the case where there are multiple roots
36     for (var i = 0, len = roots.length; i < len; ++i) {
37         findChildren(roots[i]);
38     }
39 
40     return roots;
41 }
42 
43 console.log(buildHierarchy(items));?
View Code

 

javascript算法小结

标签:

原文地址:http://www.cnblogs.com/353373440qq/p/4182021.html

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