简体   繁体   English

Function 类似于 Jquery $.grep?

[英]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. 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.我正在寻找一个类似的 function,它将 json 中看起来像“2020-12-30T08:11:35.99”的所有字符串转换为日期对象。

My Json is full of arrays that look like this:我的 Json 充满了 arrays,看起来像这样:

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.如果这样的 function 不存在,我认为可以创建一个 function 来迭代 json,然后寻找一个优雅的解决方案。

JSON.parse can take a reviver function as a parameter that can be used to transmogrify values as the JSON data is deserialised. JSON.parse可以将reviver function 作为可用于变形值的参数,因为 JSON 数据已反序列化。

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:在这种情况下,您需要一个 function 来测试每个值以查看它是否与 ISO 日期/时间格式匹配,如果匹配则返回new Date(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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM