2012-05-01 38 views
2

創建樹數據我試圖使用顯示一個jqTree樹 - http://mbraak.github.com/jqTreejqTree - 從JSON

我需要從JSON創建樹數據的幫助。

我的JSON數據是這樣的:

{ 
"d" : { 
"results": [ 
    { 
     "Title": "Committee A", 
     "ReportsToId": null, 
     "Rank": 1, 
     "Id": 5 
    }, 
    { 
     "Title": "Committee B", 
     "ReportsToId": 5, 
     "Rank": 2, 
     "Id": 7 
    }, 
    { 
     "Title": "Committee C", 
     "ReportsToId": 7, 
     "Rank": 3, 
     "Id": 13 
    }, 
    { 
     "Title": "Committee D", 
     "ReportsToId": 13, 
     "Rank": 4, 
     "Id": 1 
    }, 
    { 
     "Title": "Committee E", 
     "ReportsToId": 13, 
     "Rank": 4, 
     "Id": 3 
    } 
] 
} 
} 

我想這結束了:

var treeData = [ 
    { 
     label: 'Committee A', 
     children: [ 
      { 
       label: 'Committee B', 
       children: [ 
       { 
        label: 'Committee C', 
        children: [ 
         { label: 'Committee D' }, 
         { label: 'Committee E' } 
        ] 
       }] 
      } 
      ] 
    } 
    ]; 

回答

2

這裏是改編自http://www.jqwidgets.com/populating-jquery-tree-with-json-data/一個解決方案:

var jqTreeData = function (data) { 
     var source = []; 
     var items = []; 
     // build hierarchical source. 
     for (i = 0; i < data.length; i++) { 
      var item = data[i]; 
      var title = item["Title"]; 
      var reportsToId = item["ReportsToId"]; 
      var id = item["Id"]; 

      if (items[reportsToId]) { 
       var item = 
       { 
        label: title 
       }; 

       if (!items[reportsToId].children) { 
        items[reportsToId].children = []; 
       } 

       items[reportsToId].children[items[reportsToId].children.length] = item; 
       items[id] = item; 
      } 
      else { 
       items[id] = 
       { 
        label: title 
       }; 

       source[0] = items[id]; 
      } 
     } 
     return source; 
    } 
+0

你可以看到,請我的問題? http://stackoverflow.com/questions/11742463/how-to-format-json-in-rails-controller – byCoder

+0

@ dm80你能幫我的代碼嗎? http://jsfiddle.net/elkk/ts9v17xt/ – user525146