vue.js 需要一个包含与日期关联的请求的表

46scxncf  于 2022-11-17  发布在  Vue.js
关注(0)|答案(4)|浏览(149)

我无法得到这样的结果:我需要一个日期表(格式为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。
复杂性在于它是一个包含数组的键值字典。
而那个,我可管不了。
有人有什么想法吗?

9udxz4iz

9udxz4iz1#

使用一个函数来搜索具有相同日期的项目。如果它不存在,你可以推送该对象,如果它存在,则只将idRequest推送到requests

const index=this.daysRequest.findIndex((item) => item.day===dateArray[i]);
if (index==-1){ //index is -1 if the item isn't found
    this.daysRequest.push({
        day: dateArray[i],
        requests: [idRequest]
    });
}else{  //index is the index of daysRequest where your date is
    this.daysRequest[index].requests.push(idRequest);
}

看一下文档:Array.prototype.findIndex()

4dc9hkyq

4dc9hkyq2#

事实上,我也尝试过类似的解决方案,但我得到的结果和你的一样,也就是在控制台显示的表中,我有重复项。下面是我在循环中使用你的代码,我在循环中使用i变量作为else中daysRequest的索引:

for (let i = 0; i < dateArray.length; i++) {
    const index=this.daysRequest.findIndex((item) => item.day===dateArray[i]) ;
    if (index==-1){ //index is -1 if the item is not found
        this.daysRequest.push({
        day : dateArray[i],
        requests : [idRequest]
        }) ;
    }else{ //index is the index of daysRequest where your date is located
        this.daysRequest[i].requests.push(idRequest) ;
    }

    console.log(this.daysRequest.toString()) ;
}

我们可以看到,“Mon Nov 14 2022 00:00:00 GMT+0100”这一天是重复的,但有2个不同的请求,而不是合并

k3fezbri

k3fezbri3#

您可以使用Array.findIndex()方法沿着Destructuring assignment运算子来达成此目的。
现场演示**:**

const arr = [{
  date: '15-11-2022',
  requests: [1]
}, {
  date: '10-11-2022',
  requests: [1, 3]
}];

const objToPush = {
    date: '15-11-2022',
  requests: [5]
};

const index = arr.findIndex(item => item.date === objToPush.date);

if (index === -1) {
    arr.push(objToPush);
} else {
    arr[index].requests = [...arr[index].requests, ...objToPush.requests]
}

console.log(arr);
zu0ti5jz

zu0ti5jz4#

最后,这:

const day = dateArray[i];
 
if (!(day in this.daysRequests)) {
    // if there is no request for this day yet
    this.daysRequests[day] = [];
}
 
this.daysRequests[day].push(request_id);

它使我成为一个对象,其中每个属性都是一个请求列表。

相关问题