从给定数据中组织出父子关系结构数据
var obj = [
{id:'a',txt:'sds',from:'root1'},
{id:'b',txt:'er',from:'a'},
{id:'c',txt:'yth',from:'a'},
{id:'r',txt:'yth',from:'c'},
{id:'d',txt:'e2r',from:'b'},
{id:'e',txt:'y23th',from:'b'},
{id:'q',txt:'sds',from:'root2'},
{id:'w',txt:'er',from:'q'},
]
var tree = function(node={},objArr=[]){
var fs = objArr.filter(item=>item.from === node.id);
if(!fs||fs.length === 0){
return node;
}else{
node.children=[];
}
fs.forEach(item=>node.children.push(tree(item,objArr)));
return node;
}
var findRoot = function(objArr=[]){
var roots=[];
objArr.forEach(item=>{
var pick = objArr.find(item_=> item_.id === item.from);
if(!pick){
roots.push(item);
}
})
return roots;
}
var formatTree = function(treeFun,obj=[]){
var treeArr = [];
var roots = findRoot(obj);
roots.forEach(n=>treeArr.push(treeFun.call(this,n,obj)));
return treeArr;
}
var targets = formatTree(tree,obj);