MuffinTheMan
MuffinTheMan

Reputation: 1591

How to access object properties in a JSON file using literals obtained from the same file

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!

Upvotes: 0

Views: 2051

Answers (2)

meetamit
meetamit

Reputation: 25157

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 calling alert("2010-09".ties), which is expectedly undefined.

But, building on what Lars explained,

_.keys(data.games).forEach(function(d)
{
    alert(data.games[d].ties);
});

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.

Upvotes: 2

Lars Kotthoff
Lars Kotthoff

Reputation: 109252

You can enclose keys in [""] to access the value, i.e. alert(data.games["2010-09"].ties); will work. You might also be interested in the d3 functions to work with key-value structures; see the documentation.

Upvotes: 2

Related Questions