2014-02-21 30 views
2

我正在嘗試不同的方法到my previous question。基本上,我有一個JSON對象,看起來像這樣:重新格式化節點中的JSON樹

var data = { 
    "tree": { 
     "id": "99842", 
     "label": "Bill", 
     "children": [ 
      { 
       "id": "27878", 
       "label": "Tom", 
       "children": [] 
      } 
     ] 
    }, 
    "index": { 
     "27878": { 
      "birthdate": "1/21/1988", 
      "spouse": "June", 
      "hometown": "Tulsa, OK" 
     }, 
     "99842": { 
      "birthdate": "4/15/1969", 
      "spouse": "Mary", 
      "hometown": "Dallas, TX" 
     } 
    } 
}; 

正如你可以看到,有兩個「頂級」項目:「樹」對象和「索引」的對象。我想分析他們共同獲得此:

{ 
    "rows": [ 
     { 
      "id": "99842", 
      "data": [ 
       { 
        "birthdate": "4/15/1969", 
        "spouse": "Mary", 
        "hometown": "Dallas, TX" 
       } 
      ], 
      "rows": [ 
       { 
        "id": "27878", 
        "data": [ 
         { 
          "birthdate": "1/21/1988", 
          "spouse": "June", 
          "hometown": "Tulsa, OK" 
         } 
        ], 
        "rows": [] 
       } 
      ] 
     } 
    ] 
} 

好像我可以做遞歸與Q,但它似乎像矯枉過正,我有一個很難讓我的頭纏着。我想通過回調的解決方案,但還沒有完成。我會很感激任何幫助。

+1

那裏沒有什麼看起來異步。你爲什麼想着'Q'或回調?你不能做簡單的同步遞歸嗎? –

+0

@AaronDufour - 我想我很難讓我的頭在節點遞歸。但是,也許我讓它比實際上更難。 –

回答

3

遞歸似乎完全合理。這裏有一個可能的解決方案:

function nestObjects(tree, index) { 

    var output; 

    if (tree && index) { 

     output = { 
      id: tree.id, 
      data: index[tree.id], 
      rows: [] 
     }; 

     if (Array.isArray(tree.children) && tree.children.length) { 

      for (var i = 0, len = tree.children.length; i < len; i++) { 

       output.rows.push(nestObjects(tree.children[i], index)); 
      } 
     } 
    } 

    return output; 
} 

var result = { 
    rows: [nestObjects(data.tree, data.index)] 
}; 

console.log(result); 
+0

我有點尷尬,這很容易。我不知道爲什麼我認爲它會要求回調或者Node-ish。謝謝。 –

+0

沒有汗!我花了一段時間才把自己的頭腦包裝在異步風格的編程和回調(並知道何時不需要)。乾杯。 :) – prattsj