我目前被困在如何遍歷JSON結構(我創建)以創建並排的環形圖表。我想我已經創建了一個糟糕的結構,但會很感激任何建議。嵌套的JSON結構並排構建d3.js圖表
我正在從Mike Bostock的例子:http://bl.ocks.org/mbostock/1305337,它爲源數據使用.csv文件。
在那個例子中,他使用d3.nest()來創建一個具有一系列航班起源的嵌套數據結構。
var airports = d3.nest()
.key(function(d) { return d.origin; })
.entries(flights);
他就能夠到新的數據結構綁定到一個新的div選擇:
var svg = d3.select("body").selectAll("div")
.data(airports)
.enter().append("div")
這讓他可以爲每個航班始發地爲圓環圖。
我的JSON數據如下所示:
{"years": [
{
"year": 2015,
"type": "bestSellers",
"chartOne": [
{
"label": "smarties",
"value": 11
},
{
"label": "nerds",
"value": 13
},
{
"label": "dots",
"value": 16
},
{
"label": "sour patch kids",
"value": 61
}
],
"chartTwo": [
{
"label": "Pepsi",
"value": 36
},
{
"label": "sunkist",
"value": 13
},
{
"label": "coke",
"value": 34
}
]}
我是一個CS的學生,用的數據結構的最佳實踐和d3.js.一點經驗我創建的結構對我來說看起來並不「平坦」,所以我不確定是否需要使用d3.nest()。但是,我不清楚如何使用該結構來遍歷chartOne和chartTwo。
我可以得到圖表內的數組: var chartOne = years [0] .chartOne; var cartTwo = years [0] .chartTwo;
但我想能夠有一個對象訪問chart1和chart2。我很想在我的JSON中創建另一個數組塊,但不清楚是否沒有更簡單的方法。
謝謝回答問題和示例代碼。現在我明白了這一點對我來說完全有意義。 – AmericanCities