繁体   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. 例如:

            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.

我正在寻找一个类似的 function,它将 json 中看起来像“2020-12-30T08:11:35.99”的所有字符串转换为日期对象。

我的 Json 充满了 arrays,看起来像这样:

Total_Hours: 9.48,
Start_Time:"2020-05-18708:31:48",
 End_Time: "2020-05-18718:00:49" 

我希望它看起来像

Total_Hours: 9.48,
Start_Time: new Date("2020-05-18708:31:48"),
 End_Time: new Date("2020-05-18718:00:49") 

如果这样的 function 不存在,我认为可以创建一个 function 来迭代 json,然后寻找一个优雅的解决方案。

JSON.parse可以将reviver function 作为可用于变形值的参数,因为 JSON 数据已反序列化。

在这种情况下,您需要一个 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