简体   繁体   中英

JavaScript/D3 getFullYear() is not a function

I have dates formatted as "2020-04-01" in a JSON object. I'm converting them to dates as follows:

for(var j = 0; j < json_data.length; j++) {
       var timeParse = d3.timeParse("%Y-%m-%d");
       json_data[j]["date"] = timeParse(json_data[j]["date"])
   }

I can console.log these and they are objects: 在此处输入图像描述

I'm then using d3.nest with rollup to aggregate my data by date:

   const days =
   d3.nest()
   .key(function(d) { return d.date; })
   .rollup(function(d) { return d3.sum(d, function(d) { return d.cases; }); })
   .entries(json_data)

Then I attempt to nest again by year:

   const years =
   d3.nest()
  .key(d => d.key.getFullYear())
  .entries(days)
  .reverse()

And I get the error that getFullYear() is not a function. I'm guessing this is because at some point my data value is being converted to a string rather than an object.

That's the expected behaviour. If you look at the API , you'll see that key() :

Registers a new key function. The key function will be invoked for each element in the input array and must return a string identifier to assign the element to its group. (emphasis mine)

The obvious solution is dropping the time parse in the for loop, and using the date string as it is in the nest. Pay attention to the fact that this will probably break something else in your code, but we cannot tell it just with what you posted.

Then, in the second nest, you can use a regex or parse the date:

.key(d => timeParse(d.key).getFullYear())

Finally, have in mind (based on the quote above) that despite getFullYear() returning a number, that number will be converted to a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM