2016-09-22 85 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); 
    }, []); 
} 

謝謝大家的幫助