[英]Filter by date Javascript
I know this question is already solved in this post [FilterbyDate][1] but I'm fetching a local json file, I need to filter the json file with the date range of an input text.我知道这个问题已经在这篇文章 [FilterbyDate][1] 中得到解决,但我正在获取本地 json 文件,我需要使用输入文本的日期范围过滤 json 文件。 I have a localserver, so I already fetched the json file and display it with a console.log
我有一个本地服务器,所以我已经获取了 json 文件并用 console.log 显示它
The date structure is like this one "2020-02-01", I think that if I could assign the json fetched to a global variable it would be easier to deal with the data.日期结构类似于“2020-02-01”,我认为如果我可以将获取的 json 分配给全局变量,则处理数据会更容易。
This is like the code looks like:这就像代码的样子:
fetch('cars.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var startDate = new Date("2020-02-01");
var endDate = new Date("2020-02-29");
var resultProductData = myJson.filter(function (a) {
var hitDates = a.DATE || {};
// extract all date strings
hitDates = Object.keys(hitDates);
// improvement: use some. this is an improment because .map()
// and .filter() are walking through all elements.
// .some() stops this process if one item is found that returns true in the callback function and returns true for the whole expression
hitDateMatchExists = hitDates.some(function(dateStr) {
var date = new Date(dateStr);
return date >= startDate && date <= endDate
});
return hitDateMatchExists;
});
console.log(resultProductData);
});
Thanks for helping me, I'm new with javascript.感谢您的帮助,我是 javascript 的新手。
Hi I will answer my question, I found this solution, I hope this could help someone dealing with the same stuff of filtering by date.嗨,我会回答我的问题,我找到了这个解决方案,我希望这可以帮助处理按日期过滤的相同内容的人。
async function getData() {
var startDate = "2020-02-01";
var endDate = "2020-02-29";
const response = await fetch('file.json');
const data = await response.json();
var result = data.filter(function(obj){
return obj.DATE >= startDate && obj.DATE <= endDate;
});
console.log(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.