Reputation: 1889
I am getting some odd behavior from the D3.js nest functionality, it seems as if the key and rollup are converting the test_date from a Date object to a string.
Here is my code:
var data = [{
"test_type": "x1",
"test_date": "2014-07-15"
}, {
"test_type": "x3",
"test_date": "2014-07-16"
}, {
"test_type": "x2",
"test_date": "2014-07-27"
}, {
"test_type": "x1",
"test_date": "2014-07-28"
}];
var parseDate = d3.time.format("%Y-%m-%d").parse;
data.forEach(function(d) {
d.test_date = parseDate(d.test_date);
});
var result = d3.nest()
.key(function(d) {
return d.test_type;
})
.key(function(d) {
return d.test_date;
})
.rollup(function(leaves) {
return leaves.length;
})
.entries(data);
And the result is:
[{
"key": "x1",
"values": [{
"key": "Tue Jul 15 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}, {
"key": "Mon Jul 28 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}]
}, {
"key": "x3",
"values": [{
"key": "Wed Jul 16 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}]
}, {
"key": "x2",
"values": [{
"key": "Sun Jul 27 2014 00:00:00 GMT-0600 (Mountain Daylight Time)",
"values": 1
}]
}]
I need the nested key value to be a date object not a string. Does anybody have any idea what would cause this?
Here is a jsfiddle with the issue http://jsfiddle.net/2ryahc9L/1/
Upvotes: 3
Views: 1627
Reputation: 1
I found a solution that did work for me. I had a similar problem. I would like to nest data with a time stamp as key. AmeliaBR wrote that keys are strings. But, I would like to use the key as an object, because it should be the x-axis of my chart.
var data = [{
"test_type": "x1",
"test_date": "2014-07-15"
}, {
"test_type": "x3",
"test_date": "2014-07-16"
}, {
"test_type": "x2",
"test_date": "2014-07-27"
}, {
"test_type": "x1",
"test_date": "2014-07-15"
}];
var parseDate = d3.time.format("%Y-%m-%d").parse;
I'm using another field for date only for the key of the nested data without parsing the data as date/time.
data.forEach(function(d) {
d.key_date = d.test_date;
d.test_date = parseDate(d.test_date);
});
var result = d3.nest()
.key(function(d) {
return d.key_date;
})
.rollup(function(leaves) {
return leaves.length;
})
.entries(data);
To result
I'm adding again test_date
as an object, since key_date
is a string.
result.forEach(function(d) {
d.test_date = parseDate(d.key);
});
I have no clue if this is a good way to do it. If not, please advice. Thanks...
Upvotes: 0
Reputation: 8264
The function (and object) d3.time.format
work in two ways:
d3.time.format('%Y-%m-%d').parse('2014-08-29')
will return a Date
object. It uses the format to know how to interpret the string given as argument.d3.time.format('%Y-%m-%d')(new Date(2014, 7, 29))
will return the string, formatted as 2014-08-29'
.Besides, the keys in d3.nest
will always be coerced to strings. You will need to combine both forms to get the desired behavior. Regards.
Upvotes: 3