gpt4 book ai didi

javascript - D3嵌套格式日期不正确

转载 作者:行者123 更新时间:2023-11-29 10:42:46 24 4
gpt4 key购买 nike

我从 D3.js 嵌套功能中得到一些奇怪的行为,似乎键和汇总正在将 test_date 从 Date 对象转换为字符串。

这是我的代码:

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);

结果是:

[{
"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
}]
}]

我需要嵌套的键值是一个日期对象而不是一个字符串。有谁知道会导致这种情况的原因是什么?

这是一个问题 http://jsfiddle.net/2ryahc9L/1/ 的 jsfiddle

最佳答案

函数(和对象)d3.time.format以两种方式工作:

  • d3.time.format('%Y-%m-%d').parse('2014-08-29') 将返回一个 Date 对象.它使用格式来了解如何解释作为参数给出的字符串。
  • d3.time.format('%Y-%m-%d')(new Date(2014, 7, 29)) 将返回字符串,格式为 2014- 08-29'.

此外,d3.nest 中的键将始终被强制转换为字符串。您将需要结合这两种形式以获得所需的行为。问候。

关于javascript - D3嵌套格式日期不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25576853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com