【发布时间】:2021-08-10 14:03:49
【问题描述】:
我有这个数据集:
const data = [
{animal: 'cat', name: 'mu', date: new Date(2020, 0, 1)},
{animal: 'cat', name: 'muji', date: new Date(2021, 0, 1)},
{animal: 'cat', name: 'mine', date: new Date(2021, 0, 1)},
{animal: 'dog', name: 'fido', date: new Date(2021, 0, 1)},
{animal: 'dog', name: 'fido2', date: new Date(2020, 0, 1)},
{animal: 'dog', name: 'fido3', date: new Date(2021, 0, 1)},
{animal: 'hamster', name: 'gerry', date: new Date(2019, 0, 1)},
{animal: 't-rex', name: 'dino', date: new Date(2020, 0, 1)},
{animal: 't-rex', name: 'sauro', date: new Date(2019, 0, 1)},
{animal: 'sheep', name: 's', date: new Date(2019, 0, 1)},
{animal: 'sheep', name: 'sss', date: new Date(2019, 0, 1)},
]
它基本上是一个对象数组。每个对象都包含一个字段date 和一个日期对象。
我想要的是这样的:
const result = {
cat: {2020: 1, 2021: 2},
dog: {2020: 1, 2021: 2},
hamster: {2019: 1},
't-rex': {2019: 1, 2020: 1},
sheep: {2019: 2},
}
因此,一个对象按animal 分组,每个动物值是一个对象,其包含每年的键,值是该年份的记录数。
如您所见,cat 在 2021 年有 2 个日期,在 2020 年有 1 个日期,所以cat: {2020: 1, 2021: 2}。
我想我可以使用d3.rollup 并执行以下操作:
const result = d3.rollup(data, v => v.?, d => d.animal)
我不知道怎么用,或者也许有更聪明的解决方案,我也可以使用 Lodash。
非常感谢任何帮助!
【问题讨论】:
标签: javascript d3.js lodash