2016-09-22 71 views
0

我试图获取特定人员的后代列表。以下是我到目前为止:试图从json树状结构递归创建结果数组JavaScript

function getDescendants(id, descendants){ 
    children = getChildren(id); 
    if(children){ 
     for (var child in children) { 
      if(children.hasOwnProperty(child)){ 
       descendants.push(getDescendants(children[child].id, descendants)); 
      } 
     } 
    } 
    return getPersonById(id); 
} 

此工作,直到它返回到初始调用,并已忘记了子数组。

的getChildren回报和儿童的对象数组 getPersonById返回

任何帮助/建议表示赞赏一个人对象

+1

代码是不符合逻辑,为什么不回到'descendants'直接 –

+0

@AbdelrhmanMohamed好的想象的后代甚至没有传递想象它的全球...如果不是我们做的(儿童儿童) if(children.hasOwnProperty(child)){ descendants.push(children [child]); getDescendants(children [child] .id); } \t \t}' – HobbitMafia

+0

让我直说,你需要记住第一次调用getChildren时返回的原始数组吗?你是否想要偶然制作一棵B树? – Ryan

回答

0
function getDescendants(id, descendants, originalChildren){ 
    children = getChildren(id); 
    if(children){ 
     var originalChildren = originalChildren || children; 
     for (var child in children) { 
      if(children.hasOwnProperty(child)){ 
       descendants.push(getDescendants(children[child].id, descendants, originalChildren)); 
      } 
     } 
    } 
    return getPersonById(id); 
} 

当你第一次调用getDescendantsnull或只是不及格的东西第三个插槽。如果它为空,那么它将在变量中存储children的值,否则它将每次存储originalChildren,并且您将继续通过您的函数传递第一个children实例。

0

经过咨询一些同事和大量的脑部疼痛,这就是我们想出的。

let getDescendants = (parentID, people) => { 
    return people.filter((el)=>{ 
     return el.parents.indexOf(parentID) > -1; 
    }).map((kid)=>{ 
     return [...getDescendants(kid.id, people), kid.id ]; 
    }).reduce((a, b) => { 
     return a.concat(b); 
    }, []); 
} 

谢谢大家的帮助