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

Vue.js中如何实现多条件产品筛选的交集逻辑?

场景说明

现有如下产品数组:

[
    {
      "ID": 1,
      "Fuel Source": "Wood",
      "Type": "Freestanding",
      "Model": "F1150",
      "Catalytic": "No",
      "Maximum BTU's Per Hour": 55000,
      "Higher Heating Value Efficiency (HHV)": 0.7,
      "Lower Heating Value Efficiency (LHV)": 0.75,
      "Steady-State Efficiency": "n/a",
      "Link To Unit": "http://www.regency-fire.com/en/Products/Wood/Wood-Stoves/F1150",
      "Key Features": "Large fire viewing area, with heat radiating ceramic glass\nWood-finished handle\nHeavy duty cast hinges that will never bend or break\nSolid forged steel adjustable cam lock ensures a tight door seal over time\nFront mounted air adjustment\nAir operating safety tool\nHigh performance brick-lined firebox reflects heat\nNon-obtrusive air wash curtain keeps glass clean\nHeavy gauge steel log retainers to stop logs from rolling\nWelded ash lip will never bend or break\nRear heat deflector allowing for closer clearances\nMobile home and alcove approved\nDual-burn design creates longer and more complete burns\nBacked by the industry’s most comprehensive Limited Lifetime Warranty",
      "Product Size": "Small",
      "Maximum Log Size": "18\"",
      "Burn Time*": "Up to 8 hours",
      "Firebox Capacity": "1.3 cu. ft.",
      "Hopper Size": "n/a",
      "Emissions (g/hr)": "1.7 g/hr",
      "View Area": "126 sq. in.",
      "Exhaust Size": "6\"",
      "Minimum Fireplace Opening (W x H x D)": "n/a",
      "Fireplace Dimensions (W x H x D)": "24\" x 32-3/16\" x 20\"",
      "Picture Name": "F1150.jpg",
      "Feature Sheet File Name": "F1150 Feature Sheet.pdf",
      "Description": "The Regency Classic Small Wood Stove is perfect for smaller spaces, or for those needing to supplement their current heating system. It's compact footprint does not disappoint in heating capacity; burning efficiently, and extracting all the heat possible from one load of wood. Turn down your furnace and save money with this Regency small wood stove.",
      "Teaser": "A perfect fit for smaller rooms.  This small non-catalytic wood stove, comes with your choice of pedestal or legs and it is available in black or with nickel accents.",
      "Additional Picture Name #1": "F1150-B.jpg",
      "Pricing Reference Name": "001-915"
    },
    {
      "ID": 2,
      "Fuel Source": "Wood",
      "Type": "Freestanding",
      "Model": "F2450",
      "Catalytic": "No",
      "Maximum BTU's Per Hour": 75000,
      "Higher Heating Value Efficiency (HHV)": 0.733,
      "Lower Heating Value Efficiency (LHV)": 78.4,
      "Steady-State Efficiency": "n/a",
      "Link To Unit": "http://www.regency-fire.com/en/Products/Wood/Wood-Stoves/F2450",
      "Key Features": "Large fire viewing area, with heat radiating ceramic glass\nWood-finished handle\nHeavy duty cast hinges that will never bend or break\nSolid forged steel adjustable cam lock ensures a tight door seal over time\nFront mounted air adjustment\nAir operating safety tool\nHigh performance brick-lined firebox reflects heat\nNon-obtrusive air wash curtain keeps glass clean\nWelded ash lip will never bend or break\nRear heat deflector allowing for closer clearances\nMobile home and alcove approved\nDual-burn design creates longer and more complete burns\nBacked by the industry’s most comprehensive Limited Lifetime Warranty",
      "Product Size": "Medium",
      "Maximum Log Size": "18\"",
      "Burn Time*": "Up to 10 hours",
      "Firebox Capacity": "2.3 cu. ft.",
      "Hopper Size": "n/a",
      "Emissions (g/hr)": "2.3 g/hr",
      "View Area": "161 sq. in.",
      "Exhaust Size": "6\"",
      "Minimum Fireplace Opening (W x H x D)": "n/a",
      "Fireplace Dimensions (W x H x D)": "24\" x 36-5/16\" x 27-3/16\"",
      "Picture Name": "F2450.jpg",
      "Feature Sheet File Name": "F2450 Feature Sheet.pdf",
      "Description": "The Regency Classic Medium Wood Stove provides the perfect amount of heat for most spaces. Load wood in this stove front to back or side to side for the optimum convenience. Backed by our Limited Lifetime Warranty, we are confident that the quality workmanship, finest materials and durable construction of all Regency products, will serve your family for years to come.",
      "Teaser": "The F2450 is a Medium non-catalytic wood stove, comes with your choice of pedestal or legs and it is available in black or with nickel accents.",
      "Additional Picture Name #1": "F2450-B.jpg",
      "Additional Picture Name #2": "F2450-C.jpg",
      "Pricing Reference Name": "001-946"
    }
  ]

目前已通过循环该数组展示全部产品,同时基于产品数组生成了包含三类筛选器(燃料类型、形态、尺寸)的filters数组,初始化及选中条件收集的代码如下:

const setFilters = () => {
    filters.value = [
      {
        id: 'Fuel Source',
        name: 'Fuel Type',
        options: [...new Set(products.value.map(item => item["Fuel Source"]))].map((item) => ({ value: item, label: item, checked: false }))
      },
      {
        id: 'Type',
        name: 'Form Factor',
        options: [...new Set(products.value.map(item => item["Type"]))].map((item) => ({ value: item, label: item, checked: false }))
      },
      {
        id: 'Product Size',
        name: 'Size',
        options: [...new Set(products.value.map(item => item["Product Size"]))].map((item) => ({ value: item, label: item, checked: false }))
      },
    ];
    
    return array;
  };
const activeFilters = computed(() => {
  let array = [];
  filters.value.forEach(function(entry){ 
    entry.options.forEach(function(childEntry) {
        if(childEntry.checked == true)
        {
          array.push(childEntry);
        }
    });
  });
  return array;
})

该filters数组与页面上的三组单选框做v-model绑定,用户选中筛选选项后filters数组会同步更新。

问题需求

需编写filteredProducts计算属性,实现:

  • 无选中筛选条件时,返回全部产品数组;
  • 有选中筛选条件时,返回满足所有选中筛选条件的产品(即多条件交集筛选)。

当前的filteredProducts写法存在逻辑问题,寻求高效简洁的实现方案。当前尝试的代码如下:

const filteredProducts = computed(() => {
  if (activeFilters.length == 0){
    return products.value
  } else {
    let productsToShow = [];
    products.value.forEach(function(product){
      let criteria = [];
      filters.value.forEach(function(filter){ 
        filter.options.forEach(function(option){
          if(option.checked == true){
            if(product[filter.name] != option.value){
              //did not meet this checked filter option so add failed to list
              criteria.push(false)
            }
          }
        })
      })
      //check if any values didnt match the filter  and if not length should be 0
      if(criteria.length == 0){
        productsToShow.push(product)
      }
    });
    return array;
  }
});
解决方案

原代码存在的问题:

  1. 错误引用未定义变量array,应该返回productsToShow;
  2. 逻辑判断颠倒:仅当所有选中条件都满足时才保留产品,原代码通过criteria.length == 0的判断逻辑错误;
  3. 嵌套循环过多,执行效率低。

以下是高效简洁的实现方案:

const filteredProducts = computed(() => {
  // 无选中条件时直接返回全部产品
  if (activeFilters.value.length === 0) {
    return products.value;
  }

  // 筛选出满足所有激活条件的产品
  return products.value.filter(product => {
    return activeFilters.value.every(filter => {
      // 找到当前筛选选项对应的产品属性名
      const parentFilter = filters.value.find(f => f.options.includes(filter));
      return product[parentFilter.id] === filter.value;
    });
  });
});

方案说明

  1. 利用filter方法遍历产品数组,结合every方法确保产品满足所有激活的筛选条件,实现交集筛选;
  2. 通过find方法关联筛选选项与对应的产品属性,保证匹配逻辑的准确性;
  3. 代码结构简洁,逻辑清晰,适合当前筛选场景的性能需求。

如果需要进一步优化多选项筛选的性能(比如同一类别下多选),可以先对激活条件按属性分组:

const filteredProducts = computed(() => {
  if (activeFilters.value.length === 0) return products.value;

  // 按产品属性分组存储选中值
  const filterMap = activeFilters.value.reduce((map, filter) => {
    const parentFilter = filters.value.find(f => f.options.includes(filter));
    const prop = parentFilter.id;
    if (!map[prop]) map[prop] = new Set();
    map[prop].add(filter.value);
    return map;
  }, {});

  return products.value.filter(product => {
    return Object.entries(filterMap).every(([prop, values]) => {
      return values.has(product[prop]);
    });
  });
});

这种写法使用Set存储选中值,判断产品属性是否符合的时间复杂度为O(1),在筛选条件较多时性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:02:03