The grep function in Jquery will take in a json, and return all the parts of a json that pass a test. For example:
var entriesInDateRange = $.grep(timeEntryChartData, function (timeEntryChartData) {
return timeEntryChartData.Date_Worked >= e.value[0] && timeEntryChartData.Date_Worked <= e.value[1];
});
// This function will return all time entries that are within the range of e.value.
I am looking for a similar function that takes all the strings in the json that look like "2020-12-30T08:11:35.99" and turn them into date objects.
My Json is full of arrays that look like this:
Total_Hours: 9.48,
Start_Time:"2020-05-18708:31:48",
End_Time: "2020-05-18718:00:49"
And I would like it to look like
Total_Hours: 9.48,
Start_Time: new Date("2020-05-18708:31:48"),
End_Time: new Date("2020-05-18718:00:49")
If such a function does not exist, I think it would be possible to create a function that iterates over the json, and if key == "Start_Time", then cast it to date, but I am looking for an elegant solution.
JSON.parse
can take a reviver function as a parameter that can be used to transmogrify values as the JSON data is deserialised.
In this case you'd need a function that tests each value to see if it matches the ISO date/time format and returns new Date(value)
if so, otherwise returning the original value:
const iso8601 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ?$/
const reviveToDate = (k, v) => iso8601.test(v) ? new Date(v) : v;
let myObj = JSON.parse(myJSON, reviveToDate);
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.