[英]Javascript, JSON,D3 and accessing nested variables to create a pie chart
我需要在JSON文檔中遍歷數組的字段。 我想要的字段是能量數組中的“總計”。 這是我的示例json文檔。
[
{
"time": "01/01/2000",
"country": "USA",
"energy":
[
{"type": "coal", "total": 25, "color": "black"},
{"type": "wind", "total": 25, "color": "blue"},
{"type": "nuclear", "total": 25, "color": "yellow"}
],
"lat": 180,
"lon": 225
},
{
"time": "01/02/2000",
"country": "USA",
"energy":
[
{"type": "coal", "total": 50, "color": "black"},
{"type": "wind", "total": 50, "color": "blue"},
{"type": "nuclear", "total": 50, "color": "yellow"}
],
"lat": 180,
"lon": 225
},
{
"time": "01/03/2000",
"country": "USA",
"energy":
[
{"type": "coal", "total": 100, "color": "black"},
{"type": "wind", "total": 100, "color": "blue"},
{"type": "nuclear", "total": 100, "color": "yellow"}
],
"lat": 180,
"lon": 225
}
]
我想為每個日期創建一個餅圖,因此每個餅圖將具有“煤”,“風”和“核”總計。 我顯然無法正確訪問數據,因為我創建的圖表是煤= 25,風= 50和核= 100。
這是我的javascript的代碼段:
//beginning of test data for pie2
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
d3.json("energyFormat.json",function (data) {
data.forEach(function(d, i){
console.log("what is d.total: " + d.energy[i].total)
d.energy[i]=d.energy[i++]
})
var arc = d3.svg.arc()
.outerRadius(40)
.innerRadius(30);
var pie = d3.layout.pie()
.sort(null)
.value(function (d, i) {
//console.log("is d.total :" + d.energy[i].total )
return d.energy[i].total;
});
var g = svg.selectAll("arc")
.data(data)
.enter().append("g")
.attr("transform", function(d, i){
//console.log("what is d.lon: " + d.lon)
//console.log("what is d.energy: " + d.energy[i])
return "translate(" + d.lon + "," + d.lat + ")" });
g.append("path")
.data(pie(data))
.attr("d", arc)
.style("fill", function (d, i) {
//console.log("is this color " + d.data.energy[i].color)
return d.data.energy[i].color;
});
g.append("text")
.data(pie(data))
.attr("transform", function (d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.style("fill", "white")
.style("font-size","12px")
.text(function (d, i) {
console.log(d.data.energy[i].total);
return d.data.energy[i].type;
});
});
//end of test data for pie2
我可以看到如何在我要查找的字段中訪問特定值(data [0] .energy [0] .total),該值為5。但是如何遍歷energy [0]和那么能源[1],等等? 我使用了forEach函數,但無法正常工作。 我希望我的問題有道理。 任何幫助或指出正確的方向將不勝感激。 我一直在看這段代碼,沒有任何突破。
不確定這是否是您要的...。
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < data[i].energy.length; j++) {
console.log(data[i].energy[j].total, 'energy total')
}
}
由於您使用foreach,因此可以選擇:
data.forEach(function(element, index){
element.energy.forEach(function(element, index) {
console.log(element.total, 'energy total')
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.