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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With