我无法得到这样的结果:我需要一个日期表(格式为YYYY-MM-DD),其中每个日期都包含请求。让我解释一下,基本上我浏览了一个已经存在的日期表,其中包含我的请求的日期。在这个日期数组浏览之后,我构建了一个新数组,其中包含数组所在的日期,作为一个键,以及通过调用我的API获得的相关请求。
因此,我有一个样式的数组(在代码片段中,dateArray[i]对应于日期数组所在的日期):
下面是表daysRequests:
[{
date: dateArray[i],
requests: [idRequestX]
},
{
date: dateArray[i],
requests: [idRequestX, idRequestY]
}]
这是我在那里做的推动:
this.daysRequests.push({
day: dateArray[i],
requests: [idRequest]
});
目前,数组中的push会为我创建重复项,因为如果某个日期有多个请求,则无法在数组中查找与现有日期对应的记录,也无法在requests子数组中添加新请求。
我不知道如何检查该日期是否已经存在于表中,如果存在,则在其子表中添加新请求的id。
复杂性在于它是一个包含数组的键值字典。
而那个,我可管不了。
有人有什么想法吗?
4条答案
按热度按时间9udxz4iz1#
使用一个函数来搜索具有相同日期的项目。如果它不存在,你可以推送该对象,如果它存在,则只将
idRequest
推送到requests
。看一下文档:Array.prototype.findIndex()
4dc9hkyq2#
事实上,我也尝试过类似的解决方案,但我得到的结果和你的一样,也就是在控制台显示的表中,我有重复项。下面是我在循环中使用你的代码,我在循环中使用i变量作为else中daysRequest的索引:
我们可以看到,“Mon Nov 14 2022 00:00:00 GMT+0100”这一天是重复的,但有2个不同的请求,而不是合并
k3fezbri3#
您可以使用
Array.findIndex()
方法沿着Destructuring assignment
运算子来达成此目的。现场演示**:**
zu0ti5jz4#
最后,这:
它使我成为一个对象,其中每个属性都是一个请求列表。