Reputation: 1727
I am trying to familiarize myself with D3 and having a hard time getting data in the right format. I have an array of objects that each have a "date" key within them and I'm trying to use d3.nest to group them by date, but can't even get the example to work (taken from https://github.com/mbostock/d3/wiki/Arrays). I've watered it down to bare essentials, but the code is taken right from the d3 wiki.
var yields = [{yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm"},
{yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca"},
{yield: 27.43, variety: "Manchuria", year: 1932, site: "Morris"}]
var nest = d3.nest()
.key(function(d) { return d.year; })
.entries(yields);
According to the wiki, this should organize the data in the following structure:
[{key: 1931, values: [
{yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm"},
{yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca"}]},
{key: 1932, values: [
{yield: 27.43, variety: "Manchuria", year: 1932, site: "Morris"}]}
]
but when checking using console.dir(yields)
I get the same flat structure as before using d3.nest. Since I can't even get the example from the documentation working, I have no idea what to try next. Help a noob out?
Upvotes: 2
Views: 3697
Reputation: 36940
You want to look at nest
, not yields
. yields
is what you passed in and nest
is what you get out. yields
doesn't change.
The d3 wiki could have written things in a more readable way:
var nest = d3.nest()
.key(function(d) { return d.year; })
var nested = nest.entries(yields);
Now, nest
is an object you can reuse for similar data with year keys, and nested
is the output of one yields
. The key
function returns the nest object itself, but entries
returns new nested data.
Upvotes: 8