修復了舊帖子。我正在尋找可以幫助我獲取 JSON 陣列中過去 30 天的所有記錄的線索和解決方案(基于 date_post 欄位dd/mm/yyyy)。
我使用了 getMonth() 但由于格式不匹配,我得到了意外的輸出。有沒有辦法做到這一點而不必交換 dd 和 mm?
[
{
"id": "5537a23050b2c722f390ab60",
"thumbImage": "http://lorempixel.com/175/115",
"title": "reprehenderit nisi occaecat magna eiusmod officia qui do est culpa",
"date_posted": "19/04/2020"
}
]
uj5u.com熱心網友回復:
您需要決議日期然后使用Array.filter(或類似的東西)。這是一個例子:
const data = [
{
"id": "5537a23050b2c722f390ab60",
"thumbImage": "http://lorempixel.com/175/115",
"title": "reprehenderit nisi occaecat magna eiusmod officia qui do est culpa",
"date_posted": "19/04/2020"
},
{ "id": "2", "date_posted": "19/04/2021"},
{ "id": "2", "date_posted": "19/01/2019"},
{ "id": "2", "date_posted": "07/01/2022"},
];
const threshold = Date.now() - 30 * 24* 60 * 60 * 1000;
const filtered = data.filter(({date_posted}) => {
const [day, month, year] = date_posted.split('/');
return (new Date(`${year}-${month}-${day}`)) > threshold;
});
console.log(filtered);
uj5u.com熱心網友回復:
您不能簡單地撰寫一個回圈,遍歷您的 JSON 陣列并檢查日期是否小于 30 天?
像這樣:
var currentDay=getDay(jsonArr.at(-1));
var currentMonth=getMonth(jsonArr.at(-1));
var lastEntries=[];
foreach(jsonArr => json){
if(getDay(json) < currentDay && getMonth(json) == currentMonth ||
getDay(json) > currentDay && getMonth(json) < currentMonth){
lastEntries[]=json;
}
現在你只需要實作函式getDay()和getMonth():
function getDay(json){
return json.date_posted.string('/')[0]; // and for the getMonth() function you take the [1] instead of [0]
}
這個解決方案不是很干凈和漂亮,但它應該可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414876.html
標籤:
上一篇:Axios帖子被CORS阻止。使用CLoudinaryapi
下一篇:將訊息放入下拉串列中以做出反應
