【发布时间】:2021-05-25 18:05:36
【问题描述】:
您好,我想过滤日期范围内的数据。
{
"websiteId": "4f8b36d00000000000000001",
"date": "2019-04-01T00:00:00.000Z",
"chats": 121,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000002",
"date": "2019-04-01T00:00:00.000Z",
"chats": 13,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000003",
"date": "2019-04-01T00:00:00.000Z",
"chats": 232,
"missedChats": 9
},
{
"websiteId": "4f8b36d00000000000000004",
"date": "2019-04-01T00:00:00.000Z",
"chats": 9,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000005",
"date": "2019-04-03T00:00:00.000Z",
"chats": 0,
"missedChats": 5
},
{
"websiteId": "4f8b36d00000000000000006",
"date": "2019-04-03T00:00:00.000Z",
"chats": 10,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000007",
"date": "2019-04-01T00:00:00.000Z",
"chats": 100,
"missedChats": 1
},
{
"websiteId": "4f8b36d00000000000000008",
"date": "2019-04-01T00:00:00.000Z",
"chats": 0,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000007",
"date": "2019-04-02T00:00:00.000Z",
"chats": 0,
"missedChats": 1
},
{
"websiteId": "4f8b36d00000000000000006",
"date": "2019-04-02T00:00:00.000Z",
"chats": 100,
"missedChats": 50
}
我目前的实现
function getData(start, end) {
if (start == null && end == null) {
fetch(url)
.then((res) => res.json())
.then((data) => {
console.log(
Object.values(
data.reduce((acc, el) => {
if (!(el.websiteId in acc)) {
acc[el.websiteId] = el;
} else {
acc[el.websiteId].chats += el.chats;
acc[el.websiteId].missedChats += el.missedChats;
}
return acc;
}, {})
)
);
});
} else {
var start = new Date('2019-04-01T00:00:00.000Z').getTime();
var end = new Date('2019-04-05T00:00:00.000Z').getTime();
result = data.filter((d) => {
var time = new Date(d.date).getTime();
return start < time && time < end;
});
console.log(result);
}
}
预期输出
当我运行 getData(startDate(2019-4-01), endDate(2019-4-02)) 我应该能够获取这些日期范围之间的数据
{
"websiteId": "4f8b36d00000000000000007",
"date": "2019-04-02T00:00:00.000Z",
"chats": 100,
"missedChats": 2
},
{
"websiteId": "4f8b36d00000000000000006",
"date": "2019-04-02T00:00:00.000Z",
"chats": 110,
"missedChats": 50
}
我想在运行函数 getDate(startDate, endDate) 时获取日期范围之间的数据
【问题讨论】:
-
data.map(result => {})没有效果,所以不知道你为什么在那里。此外,if中的data似乎来自 API 调用,但在else中,data声明/分配在哪里?换句话说,你的 if 和 else 做的是完全不同的事情,看起来并不相关。 -
抱歉,忘记删除我的地图了。编辑了我的问题。
-
您的函数有
start和end作为参数,但随后它们在else部分中被重新声明为const符号。参数被忽略。 -
对不起,我没看到那部分。编辑了我的问题
-
您的
start和end日期无效:您在日期的日期部分缺少前导0。此外,end时间戳实际上在start时间戳之前:可能是错字?
标签: javascript arrays filter