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

Vue3中高效过滤含指定分类ID的嵌套产品对象

高效过滤Vue3中包含指定分类ID的产品数组

核心实现代码

在Vue3中,利用数组的filter和some方法组合,就能高效完成需求——some会在找到第一个匹配项后立即终止遍历,避免不必要的计算,是处理这类存在性检查的最优选择:

import { computed, ref } from 'vue'

// 假设你的响应式产品数组定义如下
const products = ref([
  { 
    "id": 1, 
    "item": "Product 1", 
    "productcategories": [{ "id": 300, "title": "Category300" }, { "id": 301, "title": "Category301" }]
  },
  { 
    "id": 2, 
    "item": "Product 2", 
    "productcategories": [{ "id": 200, "title": "Category200" }]
  },
  { 
    "id": 3, 
    "item": "Product 3", 
    "productcategories": [{ "id": 301, "title": "Category301" }, { "id": 309, "title": "Category309" }]
  }
])

// 计算属性实现响应式过滤,Vue3会自动缓存结果,仅在products变化时重新计算
const filteredProducts = computed(() => {
  const TARGET_ID = 301 // 把目标ID抽成常量,避免魔法值
  return products.value.filter(product => {
    return product.productcategories.some(category => category.id === TARGET_ID)
  })
})

效率说明

  • filter仅遍历一次产品数组,逐个检查每个产品
  • some对每个产品的分类列表做短路遍历:只要找到ID为301的分类,立刻停止当前产品的分类遍历,不会继续检查剩余分类,大幅减少计算量

优化建议

  1. 响应式场景用computed:上述代码用computed包裹,Vue3会自动缓存过滤结果,只有当products数组发生变化时才会重新执行过滤,避免重复计算
  2. 静态数据提前处理:如果产品数组是静态的(不会动态更新),可以直接在初始化时执行一次过滤,不需要用计算属性
  3. 超大数据集后端过滤:如果产品数量极多,建议在接口请求时就通过后端参数过滤出包含目标分类的产品,减少前端数据传输和处理压力

预期输出

执行后filteredProducts.value的结果为:

[
  { 
    "id": 1, 
    "item": "Product 1", 
    "productcategories": [{ "id": 300, "title": "Category300" }, { "id": 301, "title": "Category301" }]
  },
  { 
    "id": 3, 
    "item": "Product 3", 
    "productcategories": [{ "id": 301, "title": "Category301" }, { "id": 309, "title": "Category309" }]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:32:49