2017-05-26 57 views
2

對於給定的扁平列表如何在對象中找到深度嵌套唯一鍵的路徑並相應地分配子對象?

let list = [ 
    { 
     key: 1, 
     parent: null, 
    }, 
    { 
     key: 2, 
     parent: 1, 
    }, 
    { 
     key: 3, 
     parent: null, 
    }, 
    { 
     key: 4, 
     parent: 1, 
    }, 
    { 
     key: 5, 
     parent: 2, 
    } 
] 

如何創建一個嵌套的對象像下面的一個?

let nest = { 
    children: [ 
     { 
      key: 1, 
      children: [ 
       { 
        key: 2, 
        children: [ 
         { 
          key: 5, 
          children: [] 
         } 
        ] 
       }, 
       { 
        key: 4, 
        children: [] 
       } 
      ] 
     }, 
     { 
      key: 3, 
      children: [] 
     } 
    ] 
} 

我不知道如何解決這個問題。我想到的解決方案必須一遍又一遍遍歷列表,以檢查對象的父代是否爲空,在這種情況下,它將被指定爲頂級對象,或者該對象的父代已存在,其中如果我們獲得了父項的路徑,並將該子項分配給該父項。

P.S. 我不認爲這是任何低於

  • this檢查在一個平面物體的關鍵一式兩份。
  • this不會顯示任何會返回路徑,給定一個唯一的關鍵。
+1

我認爲你可以object.keys實現這個()函數[鏈接]:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects /對象/鍵和遞歸函數 –

回答

2

爲建設一棵樹,你可能會使用一個循環的方法,不僅利用給定的key爲建設一個節點,但使用parent以及爲建設一個節點,其中dendency是顯而易見的。

它使用其中所有鍵都usesd作爲參考對象,像

{ 
    1: { 
     key: 1, 
     children: [ 
      { 
       /**id:4**/ 
       key: 2, 
       children: [ 
        { 
         /**id:6**/ 
         key: 5, 
         children: [] 
        } 
       ] 
      }, 
      { 
       /**id:8**/ 
       key: 4, 
       children: [] 
      } 
     ] 
    }, 
    2: /**ref:4**/, 
    3: { 
     key: 3, 
     children: [] 
    }, 
    4: /**ref:8**/, 
    5: /**ref:6**/ 
} 

主要優點旁邊的單迴路是,它的工作原理與未排序的數據,因爲該結構的使用keysparent信息在一起。

var list = [{ key: 1, parent: null, }, { key: 2, parent: 1, }, { key: 3, parent: null, }, { key: 4, parent: 1, }, { key: 5, parent: 2, }], 
 
    tree = function (data, root) { 
 
     var r = [], o = {}; 
 
     data.forEach(function (a) { 
 
      var temp = { key: a.key }; 
 
      temp.children = o[a.key] && o[a.key].children || []; 
 
      o[a.key] = temp; 
 
      if (a.parent === root) { 
 
       r.push(temp); 
 
      } else { 
 
       o[a.parent] = o[a.parent] || {}; 
 
       o[a.parent].children = o[a.parent].children || []; 
 
       o[a.parent].children.push(temp); 
 
      } 
 
     }); 
 
     return r; 
 
    }(list, null), 
 
    nest = { children: tree }; 
 

 
console.log(nest);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相關問題