## javascript 从一组数组 生成一颗树？求解

jianglibo 发布于 2011/07/28 16:55

var data = [{name:'d',id:4,parentId:3},
{name:'e',id:5,parentId:4},
{name:'a',id:1,parentId:-1},
{name:'b',id:2,parentId:1},
{name:'c',id:3,parentId:55}];

var tree = [{name:'a',id:1,parentId:-1,children:[{name:'b',id:2,parentId:1}]},{name:'c',id:3,parentId:55,children:[{name:'d',id:4,parentId:3,children:[{name:'e',id:5,parentId:4}]}]}];

0
```var getTree = (function(){

var merge = function(target, source){
while(source.length > 0){
target.push(source.pop());
}
}
return function(datas){
var dataMap = {};
var dataTree = {};
while(datas.length > 0){
var data = datas.pop();
if(!data.children)
data.children = [];
if(data.parentId == -1){
dataTree[data.id] = data;
}else{
if(dataMap[data.parentId]){
var children = dataMap[data.parentId].children;
children.push(data);
}else{
dataMap[data.parentId] = {
children:[data]
};
}
}
if(data.children){
merge(datas,data.children);
}
if(dataMap[data.id]){
merge(data.children,dataMap[data.id].children);
}
dataMap[data.id] = data;

}
return dataTree;
}
})();

0

1、遍历originAry，将没有父亲的节点（根节点）找出来。保存到一个列表中，ary0

2、对于ary0里面的每一个节点，从originAry里面找出各自的儿子，并归到自己的名下。而对于这次找到的儿子们保存到ary1里面。

3依次找，直到ary0+ary1+ary..n的长度和与originAry相等，就结束。