2014-12-04 59 views
1

我正在嘗試編寫一個採用平面數據格式的函數,該數據格式使用IDparentId來建立關係。我知道我需要使用遞歸,但我需要幫助瞭解如何在特定的JSON模型中獲取它。使用JSON遞歸

這裏是平坦的源數據,這些ID是GUID,你可以看到。

 {"id":"e6168d55-1974-e411-80e0-005056971214","parentId":"","label":"OGC File List"} 

    {"id":"17168d55-1974-e411-80e0-005056971214","parentId":"e6168d55-1974-e411-80e0-005056971214","label":"Accounting"} 

    {"id":"h37s8d55-1974-e411-80e0-005056971214","parentId":"17168d55-1974-e411-80e0-005056971214","label":"Policy"} 

    {"id":"f8ke6d55-1974-e411-80e0-005056971214","parentId":"17168d55-1974-e411-80e0-005056971214","label":"Policy"} 

下面是我需要創建的模型。我只需要幫助使用屬性id:inode:它表示節點有子節點,分支節點是子對象數組。建立分支是最讓我困惑的。我很感激任何幫助或提前的方向!

[ 
     { 
      id: 'folder_1', 
      label: 'This is Folder 1', 
      inode: true, 
      open: false, 
      icon: 'folder' 
      branch: 
       [ 
        { 
         id: 'sub-item_x', 
         label: 'This is File X', 
         inode: false, 
         icon: 'file' 
        }, 
        ... 
       ] 
     }, 
     { 
      id: 'file_1', 
      label: 'This is File 1', 
      inode: false, 
      icon: 'file' 
     }, 
     ... 
    ] 

回答

2

嘗試使用此代碼:

var list = [{...},{...},...{...}]; //folder list in JSON format == JS object 
var tree = buildChildrenList(''); //find root folders first 

function buildChildrenList(parentId){ 
    var childrens = []; 
    for(var i=0;i<list.length;i++){ 
     if (list[i].parentId == parentId){ 
      childrens.push({ 
       id: list[i].id, 
       label: list[i].label, 
       inode: true, 
       open: false, 
       icon: 'folder', 
       branch: buildChildrenList(list[i].id) //this is a recursive call 
      }); 
     } 
    } 
    return childrens; 
} 
+0

我試圖現在來測試。分支:出現錯誤「缺少}」。我試圖弄清楚。 – GoBeavs 2014-12-04 17:52:46

+0

謝謝Ragnar,我希望我能夠投票10次,非常乾淨,比我的方法更簡單。 – GoBeavs 2014-12-04 17:58:07

+0

謝謝@GoBeavs :) – Ragnar 2014-12-04 18:56:21