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

Vue项目中如何按分期月数过滤多层嵌套数组结构的产品列表

Vue 产品分期过滤逻辑实现

核心实现思路

  • 遍历所有产品数组,对每个产品的嵌套installment分期数组做筛选,仅保留月份与选中值匹配的分期条目
  • 筛选完成后,若当前产品还有剩余的匹配分期条目则保留该产品,否则将该产品从结果中剔除
  • 建议通过计算属性生成过滤后的数组,不修改原始数据,避免产生副作用

具体代码实现

假设你的月份选择器绑定值为selectedMonth,原始产品数组为productList,直接在Vue的计算属性中添加如下逻辑即可:

computed: {
  filteredProducts() {
    // 选择器绑定的选中月份
    const targetMonth = this.selectedMonth
    return this.productList.reduce((result, product) => {
      // 过滤当前产品下匹配月份的分期条目
      const matchedInstallment = product.installment.filter(group => {
        // 按你给出的数据结构,每个内层数组只有1个分期对象,直接取第一个判断
        return group[0].months === targetMonth
      })
      // 有匹配的分期就组装新对象加入结果数组
      if (matchedInstallment.length) {
        result.push({
          ...product,
          installment: matchedInstallment
        })
      }
      return result
    }, [])
  }
}

之后直接在模板中渲染filteredProducts即可得到符合要求的结果。

兼容优化点

  • 如果后续内层分期数组可能存在多个对象,可将判断逻辑修改为group.some(item => item.months === targetMonth)
  • 可添加可选链操作符group?.[0]?.months做异常兼容,避免数据结构异常时报错

内容的提问来源于stack exchange,提问作者JesúsDel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:27:03