[英]How do you access an array of Objects using D3?
I have a D3 chart where I'm trying to parse an inline JSON formatted array instead of loading the data externally. 我有一个D3图表,在这里我试图解析内联JSON格式的数组,而不是从外部加载数据。
Instead of doing something like this: 而不是这样做:
d3.json("data/tsx.json", function (error, data) {
data.forEach(function (d) {
d.dateOrig = d.date;
d.date = parseDate(d.date);
d.close = +d.close;
});
I just want to parse an inline JSON formatted array like this: 我只想解析一个内联JSON格式的数组,如下所示:
var data = [
{"date":"1-May-13","close":58.13},
{"date":"30-Apr-13","close":53.98},
{"date":"27-Apr-13","close":67.00},
{"date":"26-Apr-13","close":89.70},
{"date":"25-Apr-13","close":99.00},
{"date":"24-Apr-13","close":130.28},
{"date":"23-Apr-13","close":166.70},
{"date":"20-Apr-13","close":234.98},
{"date":"19-Apr-13","close":345.44},
{"date":"18-Apr-13","close":443.34},
];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
But this doesn't work using the same code I would have used on the first method above. 但这不能使用与上面第一种方法相同的代码。
I've created a Fiddle that sort of works, but I can see that I'm parsing the array wrong and my chart elements are being created multiple times (the same number of times as the length of the array). 我已经创建了一个Fiddle之类的作品,但是我可以看到我错误地解析了数组,并且图表元素被多次创建(与数组长度相同的次数)。 This does not happen when I load my data externally.
当我从外部加载数据时,不会发生这种情况。
See my comments starting at line 35 in this Fiddle. 查看我在Fiddle中从第35行开始的评论。
http://jsfiddle.net/Critter/Hc7zD/5/ http://jsfiddle.net/Critter/Hc7zD/5/
How can I rewrite my code to parse the JSON array properly? 如何重写代码以正确解析JSON数组? I'm stumped!
我很沮丧! Thanks so much!
非常感谢!
It appears to be a typo in your code: 它似乎是您的代码中的错字:
At Line 64 or so, I think you want: 在第64行左右,我想您想要:
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
}
);
The change being terminating the forEach right there, instead of the forEach block encapsulating the remainder of the code. 更改将在此处终止forEach,而不是封装其余代码的forEach块。
Then, delete the trailing ");" 然后,删除结尾的“);” at the end of the file, and it looks right to me.
在文件末尾,对我来说看起来不错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.