7

I am receiving this JSON object:

response.myDates = [ "2017-11-19T00:00:00.000Z", "2017-12-08T00:00:00.000Z", "2017-12-25T00:00:00.000Z", "2017-12-31T00:00:00.000Z", "2018-01-01T00:00:00.000Z" ]

I would like to save all these dates (actually there are hundreds of them) in a Date array parsedDates in Javascript.

Is there a simple way to do it without a while loop?

  • 6
    response.myDates.map(Date) – gurvinder372 Nov 09 '17 at 10:52
  • Thanks for your response @gurvinder372. Very useful! –  Nov 09 '17 at 10:55
  • 1
    @musefan or simply you can use `map` – Muthu Kumaran Nov 09 '17 at 10:56
  • 1
    @musefan I bet `map` uses but not OP going to write a `loop` for this. – Muthu Kumaran Nov 09 '17 at 10:59
  • 1
    @gurvinder372: That doesn't work, [see here](https://jsfiddle.net/yagk8k46/) – musefan Nov 09 '17 at 11:00
  • @musefan yeah, i checked as well. – gurvinder372 Nov 09 '17 at 11:02
  • 1
    @musefan We are here to help... not to criticize. – Muthu Kumaran Nov 09 '17 at 11:03
  • 2
    @MuthuKumaran: Sometime you have to criticise to help. If someone is doing something wrong do you not tell them they are wrong? Would you just say "well done, keep doing that wrong thing you are doing". Yes, people often don't like criticism and they get in a huff about it, but they end up better off for it in the long run. – musefan Nov 09 '17 at 11:04
  • 1
    @musefan you deleted your comments... Now you are being nice... good! – Muthu Kumaran Nov 09 '17 at 14:06
  • 1
    @musefan oh wait... I just found a link for you to read https://stackoverflow.com/help/be-nice – Muthu Kumaran Nov 09 '17 at 17:11
  • You can add a reviver with the fetch.response.json per [how to use reviver function with fetch.response.json()](https://stackoverflow.com/questions/58463173/how-to-use-reviver-function-with-fetch-response-json). If you **know** the resonse is only dates, it could be `.then(text => JSON.parse(text, (key, value) => new Date(value)))`, but you might want to test that the value is a valid timestamp first. – RobG Jan 18 '23 at 13:24

2 Answers2

9

You can simple do a map to new Date();

let results = response.myDates.map(date => new Date(date))

Amit
  • 3,662
  • 2
  • 26
  • 34
2

Just map over your array :

const myDates = [ "2017-11-19T00:00:00.000Z", "2017-12-08T00:00:00.000Z"],
      datesArray = myDates.map( dateString => new Date(dateString) )
      
console.log(datesArray)

Note :

Surprisingly, this Stackoverflow snippet outputs an array of strings (not sure why), but if you run it in your Chrome console or in Codepen, it outputs an array of dates, as it should

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • 1
    The SO console is it's own environment, it takes some liberties when presenting human readable versions of objects. – RobG Nov 09 '17 at 11:13