[英]Filtering then sorting object array by date
I am trying to filter the json by it's start and end date by comparing it to the current date.我正在尝试通过将 json 与当前日期进行比较来过滤它的开始和结束日期。 And I want to sort the filtered json by its start date.我想按开始日期对过滤后的 json 进行排序。 Here's what I've done so far这是我到目前为止所做的
dateNow = new Date();
filteredJson = ufjson.filter((item, index) => item.start_date <= dateNow && item.end_date <= dateNow);
However the filter doesn't work.但是过滤器不起作用。 I dont get results.我没有得到结果。
Here's my sample json这是我的样品 json
ufjson = [
{
amount: '50',
discount: '0',
start_date: '2021-01-01T18:24:18.790+08:00',
end_date: '2020-01-29T18:24:18.790+08:00',
},
{
amount: '100',
discount: '10',
start_date: '2021-01-05T18:24:18.790+08:00',
end_date: '2020-01-25T18:24:18.790+08:00',
},
]
What you did was comparing two string.你所做的是比较两个字符串。 You first have to change them to Number.您首先必须将它们更改为数字。 You can do this:你可以这样做:
var ufjson = [
{
amount: "50",
discount: "0",
start_date: "2021-01-01T18:24:18.790+08:00",
end_date: "2020-01-29T18:24:18.790+08:00",
},
{
amount: "100",
discount: "10",
start_date: "2021-01-21T18:24:18.790+08:00",
end_date: "2020-01-25T18:24:18.790+08:00",
},
];
var dateNow = new Date();
var filteredJson = ufjson.filter(
(item, index) =>
new Date(item.start_date).getTime() <= dateNow.getTime() &&
new Date(item.end_date).getTime() <= dateNow.getTime()
);
console.log("item:", filteredJson);
I just changed second date start.我刚刚更改了第二个日期开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.