How do you access an array of Objects using D3?

23,294

It appears to be a typo in your code:

At Line 64 or so, I think you want:

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.

Then, delete the trailing ");" at the end of the file, and it looks right to me.

Share:
23,294
Critter
Author by

Critter

Updated on January 20, 2020

Comments

  • Critter
    Critter over 4 years

    I have a D3 chart where I'm trying to parse an inline JSON formatted array instead of loading the data externally.

    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:

    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.

    See my comments starting at line 35 in this Fiddle.

    http://jsfiddle.net/Critter/Hc7zD/5/

    How can I rewrite my code to parse the JSON array properly? I'm stumped! Thanks so much!

  • Critter
    Critter over 10 years
    And this is why having another set of eyes can help big time! Such a simple thing can cause so much grief after 12 hours of staring at code. Thanks so much cmonkey.