因此,我的代码中包含以下功能:
filterByWeek(data) {
// so just like with the days, here we want to get a limited amount of data (last 6 weeks or less);
const weeksAgo6 = moment().startOf('week').subtract(6, 'weeks').toDate();
console.log('data', data);
const filteredData = data.filter((item) => moment(item.date).isAfter(weeksAgo6));
console.log('filter test1', data.filter((item) => moment(item.date).isAfter(weeksAgo6)));
console.log('filter test2', filteredData);
return filteredData;
}
和data参数是一个数组,其中包含如下所示的对象:
{
date: "2019-07-21T14:03:37.759Z",
_id: "5d3b29e7e7e5db358c4ec482",
exercise: "5d35da3142c6445078cd03f2",
oneRM: 93
}
此数组中所有对象的
我想用早于6周前的日期过滤掉这些对象。我使用Array.filter()函数执行此操作。并且基于console.log filter test 1
,它应该可以工作。但是,然后我尝试console.log filter test 2
,它返回一个空数组。有人知道是什么原因造成的吗?
结果console.log filter test 1
:我期望的结果
[{
"date": "2019-07-20T14:03:37.759Z",
"_id": "5d3b0876e7e5db358c4ec47b",
"exercise": "5d35da3142c6445078cd03f2",
"oneRM": 86
},
{
"date": "2019-07-21T14:03:37.759Z",
"_id": "5d3b29e7e7e5db358c4ec482",
"exercise": "5d35da3142c6445078cd03f2",
"oneRM": 93
},
{
"date": "2019-07-24T14:03:37.759Z",
"_id": "5d3b3896e7e5db358c4ec48b",
"exercise": "5d35da3142c6445078cd03f2",
"oneRM": 89
}]
结果console.log filter test 2
:一个空数组,即使我以为我记录了同样的内容
答案 0 :(得分:-1)
无法重现您的问题,两个(test1&test2)console.log
语句都记录相同的输出:
const data = [{
"date": "2019-07-20T14:03:37.759Z",
"_id": "5d3b0876e7e5db358c4ec47b",
"exercise": "5d35da3142c6445078cd03f2",
"oneRM": 86
},
{
"date": "2019-07-21T14:03:37.759Z",
"_id": "5d3b29e7e7e5db358c4ec482",
"exercise": "5d35da3142c6445078cd03f2",
"oneRM": 93
},
{
"date": "2019-07-24T14:03:37.759Z",
"_id": "5d3b3896e7e5db358c4ec48b",
"exercise": "5d35da3142c6445078cd03f2",
"oneRM": 89
}];
function filterByWeek(data) {
// so just like with the days, here we want to get a limited amount of data (last 6 weeks or less);
const weeksAgo6 = moment().startOf('week').subtract(6, 'weeks').toDate();
console.log('data', data);
const filteredData = data.filter((item) => moment(item.date).isAfter(weeksAgo6));
console.log('filter test1', data.filter((item) => moment(item.date).isAfter(weeksAgo6)));
console.log('filter test2', filteredData);
return filteredData;
};
filterByWeek(data);
<script src="https://cdn.jsdelivr.net/npm/moment@2.24.0/min/moment.min.js"></script>