2017-08-03 75 views
0

我有一個JavaScript函數,它將一個平坦的樹列表變成多維數組。我想這個函數也爲每個項目添加一個tree_level屬性。獲取樹列表級別 - JavaScript

function getNestedChildren(arr, parent) { 
    var out = [] 
    for (var i in arr) {  
      if (arr[i].headerId == parent) { 
       var children = getNestedChildren(arr, arr[i].workID) 

       if (children.length) { 
        arr[i].children = children 
       } 
       out.push(arr[i]) 
      } 
    } 
    return out 
} 

回答

1

添加樹級參數:

function getNestedChildren(arr, parent, level) { 
    var out = [] 
    for (var i in arr) { 
      if (arr[i].headerId == parent) { 
       arr[i].level = level; 

       var children = getNestedChildren(arr, arr[i].workID, level + 1) 

       if (children.length) { 
        arr[i].children = children 
       } 
       out.push(arr[i]) 
      } 
    } 
    return out 
} 
+0

這是給最後一個級別值的所有項目 – Khalil

+0

只是轉移在IF語句級別賦值語句,它的工作 – Khalil

+0

我編輯我的答案。 –

0

您最初的功能去到n陣n次,變異它的參數。

爲O(n)ES6的解決方案,不發生變異它的參數:

function getNestedChildren(arr, root) { 
    const empty = []; 
    const childrenOf = {}; 

    // build a dictionary containing all nodes keyed on parent 
    arr.forEach((node) => { 
     if (!childrenOf[node.headerId]) childrenOf[node.headerId] = []; 
     childrenOf[node.headerId].push(node); 
    }); 

    // attach children to their parents and decorate with level 
    const iterateHash = (parent, level) => { 
     const nodes = childrenOf[parent] || empty; 
     return nodes.map((node) => { 
      const children = iterateHash(node.workId, level + 1); 
      // remove the first argument {} to mutate arr 
      return Object.assign({}, node, { level, children }); 
     }); 
    }; 

    return iterateHash(root, 0); 
}