2017-02-12 270 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.)