You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用forEach过滤数据后无法向新数组推送符合条件的内容?

问题:过滤嵌套数组中日期小于当前日期的项

我有一个包含嵌套数组的数组,嵌套数组里的对象包含name和reservationDate字段,希望创建新数组存储原数组中reservationDate小于当前日期的项。

编写的Vue代码如下:

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)
      }
    })
  }
}

运行后currentReservations始终为空数组,但明明有符合日期条件的项。需要用forEach处理数据,传入Bootstrap Table使用:

<b-table striped hover :items="currentReservations"></b-table>

问题原因

  1. 错误访问数组属性:reservation.guests是数组,不是单个对象,直接写reservation.guests.reservationDate会得到undefined,undefined和字符串格式的日期比较永远为false,所以不会向currentReservations中添加任何内容。
  2. 日期比较不够可靠:直接用字符串比较YYYY-MM-DD格式的日期虽然能生效,但如果日期包含时间部分就会出错,用moment的日期方法更稳妥。

修正方案

方案1:直接筛选符合条件的guest对象(适合表格直接展示guest数据)

sortDates() {
  this.currentReservations = [];
  // 取当前日期的开始时刻,避免时间部分干扰比较
  const currentMoment = moment().startOf('day');
  
  this.reservations.forEach(reservation => {
    // 过滤当前reservation中日期符合条件的guest
    const validGuests = reservation.guests.filter(guest => {
      return moment(guest.reservationDate).isBefore(currentMoment);
    });
    // 将符合条件的guest加入结果数组
    this.currentReservations.push(...validGuests);
  });
}

方案2:保留外层结构(保留包含有效guest的reservations对象)

如果需要保留原数据的外层结构,只筛选每个reservations下符合条件的guests:

sortDates() {
  this.currentReservations = [];
  const currentMoment = moment().startOf('day');
  
  this.reservations.forEach(reservation => {
    const validGuests = reservation.guests.filter(guest => {
      return moment(guest.reservationDate).isBefore(currentMoment);
    });
    // 只有当存在有效guest时,才添加到结果数组
    if (validGuests.length > 0) {
      this.currentReservations.push({
        ...reservation, // 复制原对象的其他属性
        guests: validGuests // 替换为筛选后的guest数组
      });
    }
  });
}

内容的提问来源于stack exchange,提问作者Cphml444

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 19:14:58