Skip to content

Instantly share code, notes, and snippets.

@lvluu
Last active March 31, 2023 03:37
Show Gist options
  • Select an option

  • Save lvluu/1ab3d8136f43ef9d90c94d14d07b18c7 to your computer and use it in GitHub Desktop.

Select an option

Save lvluu/1ab3d8136f43ef9d90c94d14d07b18c7 to your computer and use it in GitHub Desktop.
JSON.parse() with nested Date type properties
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