簡體   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