Last active
March 31, 2023 03:37
-
-
Save lvluu/1ab3d8136f43ef9d90c94d14d07b18c7 to your computer and use it in GitHub Desktop.
JSON.parse() with nested Date type properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const moment = require("moment"); | |
| const dummy = { d: { d1: new Date() } }; | |
| function isDateString(value) { | |
| return ( | |
| typeof value === "string" && | |
| moment(value, moment.ISO_8601, true).isValid() && | |
| value.length >= 6 | |
| ); | |
| } | |
| function dateReviewer(_, value) { | |
| if (isDateString(value)) { | |
| return moment(value).toDate(); | |
| } | |
| return value; | |
| } | |
| console.log(dummy); // { d: { d1: 2023-03-28T12:42:16.144Z } } | |
| console.log(JSON.parse(JSON.stringify(dummy), dateReviewer)); // { d: { d1: 2023-03-28T12:42:16.144Z } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment