I’m trying to create a stacked bar chart with d3 from data in a JSON file. Each bar would have ties, losses, and wins for a particular month.
JSON file:
{
"name": "FHS",
"points": 3000,
"ties": 3,
"losses": 19,
"wins": 50,
"games": {
"2010-09": { "ties": 1, "losses": 2, "wins": 16 },
"2010-10": { "ties": 2, "losses": 5, "wins": 13 },
"2010-11": { "ties": 0, "losses": 12, "wins": 21 }
}
}
I’ve already used some of the data just fine using the d3.json functionality. For example:
d3.json("data.json",function(error,data)
{
alert(data.name);
alert(data.points);
// etc.
});
But here’s where it gets interesting (fyi, I’m using the underscore library to grab each property of “games”…perhaps this is where I’m going wrong?). If I try the following:
_.keys(data.games).forEach(function(d)
{
alert(d);
});
I get 2010-09, 2010-10, 2010-11 in three different alert boxes…perfect! BUT, if I try the following:
_.keys(data.games).forEach(function(d)
{
alert(d.ties);
});
I get undefined :/ In fact, another problem that I see arising is that
alert(data.games.2010-09.ties);
should work (if the property names didn’t begin with integers or have hyphens…), but won’t because of the format of the literal (“2010-09”)…so, my main question is how to dynamically access nested object properties in such a manner that would make generating a chart simple. I’ve tried to include enough context, but please let me know if you would like any more information. Thanks in advance!
You get undefined in the alert box because
d, inside this function, is a string – “2010-09”, “2010-10”, “2010-11”, etc – since you’re iterating over the array of strings returned by_.keys(data.games).So,
alert(d.ties)is like callingalert("2010-09".ties), which is expectedly undefined.But, building on what Lars explained,
is how you’d get at the data.
P.S.
console.log(data.games[d].ties)is the more robust way (and hence usually the preferred way) to debug javascript.