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

JavaScript过滤嵌套对象数组时无法访问periodos内层数组怎么办

问题原因

过滤逻辑无法正常运行的核心错误是属性访问层级不对:periodos是存储时段的子数组,不是单个对象,直接通过transpId.periodos.ativo这类写法访问属性,实际是在数组对象本身查找属性,只会返回undefined,所有判断条件永远无法命中。

修正方案

过滤外层配送项时,需要先遍历对应配送项的periodos子数组,判断是否存在至少一个满足全部筛选规则的时段子项,符合要求就保留该配送项。这里用数组原生some()方法做子项匹配即可,修正后的完整代码如下:

filterPeriodos() {
  let object = this.formGeral.value.data;
  let jsDate = new Date(object.singleDate?.jsDate);
  jsDate.setUTCHours(23,59,59,999);
  this.dataFormat = jsDate
  const d = new Date(jsDate);
  const currentWeekIndex = d.getDay();
  const currentMetodoId = this.metodoId;

  if (this.storeS.layout.emp.id === 1 && this.formGeral.value.entregaBool) {
    return this.transporte.filter(transporte => {
      return transporte.periodos.some(periodo => {
        return periodo.ativo === 1
          && periodo.transporte_id === currentMetodoId
          && periodo.week[currentWeekIndex] === 1
      })
    })
  }
  return this.transporte;
}
可选扩展

如果筛选后需要同步剔除每个配送项里不符合条件的时段,只保留命中规则的periodos子项,可以把过滤逻辑调整为如下写法:

if (this.storeS.layout.emp.id === 1 && this.formGeral.value.entregaBool) {
  return this.transporte
    .map(transporte => {
      // 先过滤出当前配送项下符合条件的时段
      const validPeriodos = transporte.periodos.filter(periodo => {
        return periodo.ativo === 1
          && periodo.transporte_id === currentMetodoId
          && periodo.week[currentWeekIndex] === 1
      })
      // 存在有效时段才返回带过滤后时段的配送项,否则返回null
      return validPeriodos.length ? {...transporte, periodos: validPeriodos} : null
    })
    .filter(Boolean) // 剔除没有有效时段的null项
}

注:d.getDay()返回值范围为0(周日)到6(周六),和示例JSON中week数组的索引顺序完全匹配,不需要额外做偏移处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:43:13