2013-08-05 23 views
0

我從JSON獲取數據試圖讓d3.js第一子元素的第一加載時間

{ 
    "name": "abcd", "size": 150000, 
     "children": [ 

        { 
        "name": "Modules", "size": 100000, 
        "children": [ 
        {"name": "Audio Library", "size": 100000, "info": "hello", "image": "http://s3.amazonaws.com/web2tools-production/images/199/Google_logo.PNG"}, 
        {"name": "CommentBox", "size": 100000, "info": "hi" }, 
        {"name": "Localization", "size": 100000, "info": "hi there"} 
           ] 
           }, 
           { 
           "name": "Features", "size": 100000, 
        "children": [ 
        {"name": "Rapid Development", "size": 100000, "info": "hello", "image": "http://s3.amazonaws.com/web2tools-production/images/199/Google_logo.PNG"}, 
        {"name": "User friendly interface", "size": 100000, "info": "hi" }, 
        {"name": "Highly Customizable", "size": 100000, "info": "hi there"}, 
        {"name": "Full control", "size": 100000, "info": "hi" }, 
        {"name": "Open Source", "size": 100000, "info": "hi there"} 
           ] 
        } 


        ]  

} 

我現在想用d3.js 得到「可摺疊力佈局」效果http://bl.ocks.org/mbostock/1093130

但我想只在第一次加載時加載第一個子元素。

在我的情況

  • 第一根-----> ABCD第一個孩子---->模塊二孩--->特點

我使用扁平化函數來獲取json的所有節點

function flatten(root) { 
      var nodes = [], i = 0; 

      function recurse(node) { 
       if (node.children) node.children.forEach(recurse); 
       if (!node.id) node.id = ++i; 
       nodes.push(node); 
      } 
      recurse(root); 
      return nodes; 
     } 

現在,我該如何從此函數獲取第一個子元素。 我剛剛對d3.js感興趣,對此有點困惑。

回答

0

如果你只是想頂層子元素作爲一種特殊情況,不能你剛纔訪問root.children

如果你想返回任意的級別,你可以添加一個級別限制的遞歸函數。類似(未經測試):

function flatten(root, level) { 
    level = level !== undefined ? level : 1; 
    var nodes = [], i = 0; 

    function recurse(node, currentLevel) { 
     currentLevel !== undefined ? currentLevel : 1; 
     if (node.children && currentLevel < level) { 
      node.children.forEach(function(child) { 
       recurse(child, currentLevel+1); 
      }); 
     } 
     if (!node.id) node.id = ++i; 
     nodes.push(node); 
    } 
    recurse(root); 
    return nodes; 
}