【发布时间】:2015-08-09 20:44:01
【问题描述】:
我需要遍历我的 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 中的 sn-p:
//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 函数,但我无法让它工作。我希望我的问题是有道理的。任何帮助或指向正确方向将不胜感激。我一直在看这段代码有一段时间没有突破。
【问题讨论】:
-
为此折腾一把,否则,我发现这可能会提供一些提示,说明如何引用嵌套数据stackoverflow.com/questions/21733536/…
标签: javascript json d3.js