json 如何使用 D3 访问对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18753196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you access an array of Objects using D3?
提问by Critter
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). This does not happen when I load my data externally.
我已经创建了一个类似的 Fiddle,但是我可以看到我解析的数组是错误的,并且我的图表元素被多次创建(与数组长度相同的次数)。当我从外部加载数据时不会发生这种情况。
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? I'm stumped! Thanks so much!
如何重写我的代码以正确解析 JSON 数组?我难住了!非常感谢!
采纳答案by cmonkey
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.
然后,删除尾随的“);” 在文件的末尾,在我看来是正确的。

