Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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!

like image 388
Critter Avatar asked Sep 11 '13 23:09

Critter


People also ask

How do you access arrays of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

How do you access an array of objects in Node JS?

You need to look at the structure. An Object will start with an { and an Array will start with a [ . When you see an Object, you can use . propertyName to access propertyName .

What does d3 stack do?

The d3. stack() method constructs a new stack generator with the default settings. This stack generator can be further used to create stacks.

What is d3 bisector?

The bisector() Function in D3. js is used to returns a new bisector using the specified accessor or comparator function. This method can be used to bisect arrays of objects instead of being limited to simple arrays of primitives. Syntax: d3.bisector(accessor) d3.bisector(comparator)


1 Answers

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.

like image 89
cmonkey Avatar answered Sep 19 '22 09:09

cmonkey