Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - Function similar to Jquery $.grep?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}-dd-ddTdd:dd:ddZ?$/
const reviveToDate = (k, v) => iso8601.test(v) ? new Date(v) : v;

let myObj = JSON.parse(myJSON, reviveToDate);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...