首页 > 代码库 > javascript算法小结
javascript算法小结
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 parent17 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 tree26 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 roots36 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));?
javascript算法小结
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。