我正在尝试使用D3JS中带有JSON的嵌套数组,并且无法弄清楚为什么在这个世界中我得到一个“属性长度未定义”错误,该行显示为:
.attr("d", function(d) { return line(d.points); }).
这是JSON:
[
{
"aspectRatio": 1.247386759581881,
"closed": 1,
"xyData": [
{
"x0": 0.53078594712060867,
"x1": 0.95454545454545459,
"x2": 0.95454545454545459,
"x3": 0.53078594712060867,
"x4": 0.53078594712060867,
"y0": 0.52936622215603868,
"y1": 0.52936622215603868,
"y2": 0.13179275296659432,
"y3": 0.13179275296659432,
"y4": 0.52936622215603868
}
]
},
{
"aspectRatio": 1.247386759581881,
"closed": 1,
"xyData": [
{
"x0": 0.045454545454545435,
"x1": 0.41126403477001078,
"x2": 0.41126403477001078,
"x3": 0.045454545454545435,
"x4": 0.045454545454545435,
"y0": 0.86820724703340568,
"y1": 0.86820724703340568,
"y2": 0.44804437618547044,
"y3": 0.44804437618547044,
"y4": 0.86820724703340568
}
]
}
]
这是代码:
function loadEss(filename,svgName,mainWidth){
var svgName;
d3.json(filename, function(error, data) {
data.forEach(function(kv){
kv.xyData.forEach(function(d) {
d.points = [];
aspect=1.5;
for (var i = 0; d["x"+i] !== "" && (typeof d["x"+i] !== 'undefined'); i++) {
d.points.push([mainWidth*d["x"+i], mainWidth/aspect*(d["y"+i])]);
}
console.log(d.points);
});
});
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = mainWidth - margin.left - margin.right,
height = mainWidth/aspect - margin.top - margin.bottom;
svgName= d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var line =
d3.svg.line()
.interpolate("linear-closed")
;
svgName.selectAll("path")
.data(data)
.enter()
.append("path")
;
svgName.selectAll("path")
.attr("d", function(d) { return line(d.points); })
.attr("stroke-linecap","round")
.attr("stroke-linejoin","round")
;
});
};
这项工作基于前两个主题:Nested JSON array and D3JS和d3JS: Drawing Line Segments from CSV
非常感谢任何帮助。
答案 0 :(得分:1)
这是jsfiddle
您正在构建的那些点数存储在错误的位置,因此当您将d.points
传递给line()
时,d.points
下面的点数为空。而不是kv.points
您需要 kv.xyData.forEach(function(d) {
kv.points = [];
aspect=1.5;
for (var i = 0; d["x"+i] !== "" && (typeof d["x"+i] !== 'undefined'); i++) {
kv.points.push([mainWidth*d["x"+i], mainWidth/aspect*(d["y"+i])]);
}
console.log(kv.points);
});
:
{{1}}