2017-02-12 272 views
0

我有一個數據數組,看起來像這樣:D3.js - 訪問數據嵌套數組

var data = [ 
    { 
    "key": "user", 
    "values": [ 
     "roles", 
     "manager", 
     "otherRoles", 
     "reports", 
     "devices", 
     "coffees" 
    ] 
    }, 
    { 
    "key": "role", 
    "values": [ 
     "assignments", 
     "members", 
     "otherMembers" 
    ] 
    }, 
    { 
    "key": "assignment", 
    "values": [ 
     "roles" 
    ] 
    }, 
    { 
    "key": "Device", 
    "values": [ 
     "owners", 
     "roles" 
    ] 
    }, 
    { 
    "key": "Coffee", 
    "values": [ 
     "drinkers" 
    ] 
    } 
]; 

我試圖呈現從SVG矩形所在的表頭是「關鍵」表和錶行是「值」。我能夠完成這項工作的唯一方法是爲每個表(table0,table1等)提供一個唯一的增量類。我知道這很糟糕,並且阻止我在將來輕鬆訪問所有表。下面是相關代碼:

   parentBox = svgContainer.selectAll('.table') 
        .data(data, function(d) {return d.key;}) 
        .enter() 
        .append('g') 
        .attr('class', function(d, i) { 
         return "table" + i; 
        }) 
        .attr("transform", function(d, i) { 
         return "translate(" + boxWidth*i + "," + rowHeight*i + ")"; 
        }); 

我想弄清楚D3訪問嵌套數據的正確途徑。這裏是代碼的完整:D3 Example

回答

1

原來的解決方案只需要更好地理解選擇。我首先創建parentBox容器:

parentBox = svgContainer.selectAll('.table') 
    .data(data, function(d) {return d.key;}) 
    .enter() 
    .append('g') 
    .attr('class', 'table') (etc.) 

然後,行填充表時我首先選擇創建的表,通過各表中使用的每一種方法來循環和創建的每一行。一個技巧是使用d3.select(this)來確保行已正確創建。

   svgContainer.selectAll('.table') 
       .each(function (d, i) { 
        tableRows = d3.select(this).selectAll('.row') 
         .data(d.values) 
         .enter() 
         .append(g) (etc.)