首页 > 编程语言 > 详细

javascript算法小结

时间:2014-12-24 13:05:45      阅读:256      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!