英文:
Why can I not push data to new object after filtering it with forEach?
问题
Sure, here's the translated code portion without the code itself:
我有一个包含另一个数组的数组,其中包含一个名称和一个日期。
我想创建一个第二个对象,其中包含数组中日期小于当前日期的项目。
因此,我执行了以下操作:
data() {
return {
currentDate: moment().locale(this.$i18n.locale).format('YYYY-MM-DD'),
currentReservations: [],
reservations: [
{
guests: [
{
name: 'John',
reservationDate: '2023-06-01'
},
{
name: 'Bob',
reservationDate: '2023-06-30'
}
]
}
]
};
},
methods: {
sortDates(){
const active = this.reservations;
active.forEach(reservation => {
if(reservation.guests.reservationDate < this.currentDate){
this.currentReservations.push(reservation)
}
})
}
}
如果运行此方法,即使有小于当前日期的日期,它也会返回一个空数组。
如果我使用v-for,我可以让它起作用,但我需要使用forEach,因为我需要在类似以下的Bootstrap表中返回过滤后的数据:
<b-table striped hover :items="currentReservations"></b-table>
英文:
I have a an array that contain another array, which contains a name and a data.
I would like to to create a second object that contains items from the array where the date is less than the current date.
So I did the following:
data() {
return {
currentDate: moment().locale(this.$i18n.locale).format('YYYY-MM-DD'),
currentReservations: [],
reservations: [
{
guests: [
{
name: 'John',
reservationDate: '2023-06-01'
},
{
name: 'Bob',
reservationDate: '2023-06-30'
}
]
}
]
};
},
methods: {
sortDates(){
const active = this.reservations;
active.forEach(reservation => {
if(reservation.guests.reservationDate < this.currentDate){
this.currentReservations.push(reservation)
}
})
}
}
If I run this method, it just returns an empty array, even if there are dates that are less the current date.
I can get it to work if I use v-for, but I need to do a forEach, because I will need to return the filtered data in a bootstrap table like so:
<b-table striped hover :items="currentReservations"></b-table>
答案1
得分: 3
你可以简单地使用一个计算属性:
computed: {
currentReservations() {
return this.reservations.filter((reservation) => reservation.guests.reservationDate < this.currentDate);
},
},
英文:
You can simply use a computed:
computed: {
currentReservations() {
return this.reservations.filter((reservation) => reservation.guests.reservationDate < this.currentDate);
},
},
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论