3 ms·
That's false. If you use JSON.stringify on an object, it will call the method toJSON of each values recursively. The toJSON method of a Date returns the ISO str
by simlevesque 8y ago
That's false. If you use JSON.stringify on an object, it will call the method toJSON of each values recursively. The toJSON method of a Date returns the ISO string.
source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- negativegate 8y agoBut JSON.parse will leave it as a string instead of converting it back to a date, so this cloning approach doesn't work for objects containing dates.
- simlevesque 8y agoI did not say that JSON.parse would parse the dates. I'm saying that the article is wrong when it says that JSON.stringify does not transform Dates into ISO string. Right after that, the article says "cannot be parsed back to its original value" when it definitely can be parsed back. JSON.parse does not do it by default but that was never his point.
- twblalock 8y ago> Right after that, the article says "cannot be parsed back to its original value" when it definitely can be parsed back. JSON.parse does not do it by default but that was never his point. The broader point, which is entirely correct, is that you don't get back an exact copy of the object you want to clone, because the date fields don't end up being the same type.
- freeopinion 8y agoJSON.parse of an ISO string yields a string, not a date. let d = new Date(); let s = JSON.parse(JSON.stringify(d)); s will not be a clone of d.
- simlevesque 8y agoI never said that JSON.parse yields a date by default. But it can. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Parameters https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... The article says it does not return a ISO string. I'm saying it does. The author as agreed with me and will update the article.