Javascript D3.js-访问嵌套数组中的数据
我有一个如下所示的数据数组:Javascript D3.js-访问嵌套数组中的数据,javascript,d3.js,svg,Javascript,D3.js,Svg,我有一个如下所示的数据数组: var data = [ { "key": "user", "values": [ "roles", "manager", "otherRoles", "reports", "devices", "coffees" ] }, { "key": "role", "values": [ "assignments",
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矩形中呈现表格,其中表格标题是“键”,表格行是“值”。我能够做到这一点的唯一方法是为每个表(表0、表1等)提供一个唯一的增量类。我知道这很糟糕,并且阻止我将来轻松访问所有表。以下是相关代码:
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中嵌套数据的正确方法。下面是完整的代码:结果表明,解决方案只需要更好地理解选择。我首先创建了parentBox容器:
parentBox = svgContainer.selectAll('.table')
.data(data, function(d) {return d.key;})
.enter()
.append('g')
.attr('class', 'table') (etc.)
然后,在用行填充表时,我首先选择创建的表,使用each方法循环遍历每个表并创建每一行。一个技巧是使用d3。选择(this)以确保正确创建行
svgContainer.selectAll('.table')
.each(function (d, i) {
tableRows = d3.select(this).selectAll('.row')
.data(d.values)
.enter()
.append(g) (etc.)
事实证明,解决方案只需要更好地理解选择。我首先创建了parentBox容器:
parentBox = svgContainer.selectAll('.table')
.data(data, function(d) {return d.key;})
.enter()
.append('g')
.attr('class', 'table') (etc.)
然后,在用行填充表时,我首先选择创建的表,使用each方法循环遍历每个表并创建每一行。一个技巧是使用d3。选择(this)以确保正确创建行
svgContainer.selectAll('.table')
.each(function (d, i) {
tableRows = d3.select(this).selectAll('.row')
.data(d.values)
.enter()
.append(g) (etc.)