我的 json 数据中有嵌套数组,但我不知道如何在 d3 中调用它们(初学者)。
在下面的示例中,我尝试使用 Json 中嵌套在“膳食”数组中的“January”数组中的数据来构建 SVG 条形图。
Json 看起来像这样:
{
"meals":[
{"january":[
{},{}
]},
{"february":[
{},{}
]},
{"march":[
{},{}
]},
}
d3 代码如下所示。 “图表”接受下拉菜单的用户输入。在这种情况下,它基本上返回“餐点”:
var chart = selection.options[selection.selectedIndex].id;
var dataset = data[chart];
var svg = d3.select ("body")
.append ("svg")
.attr("width", w)
.attr("height", svgHeight+30);
svg.selectAll("rect")
.data(dataset.january) //***HERE is where I'm having trouble***
.enter()
.append("rect")
最佳答案
d3.nest()
可以将这样的数据转换为可解析的数组。这些“教程”示例很棒:http://bl.ocks.org/phoebebright/raw/3176159/
鉴于您的项目是可行的,否则最好简单地更改数据格式以便于遍历,例如
{
"meals":[
{"name":"salad","month":"january"},
{"name":"burger","month":"february"}, //etc...
关于javascript - 如何使用 d3 从嵌套的 JSON 数组中调用数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556981/