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

Angular 8中如何根据多选下拉框值过滤API响应结果

修改后的代码及说明

原代码的问题在于:

  1. 多选下拉框选中多个选项时,this.makeLineForm.controls['businessGroup'].value 返回数组,但原代码直接对其调用 toLowerCase(),会将数组转为字符串(如 "[Home Care, Personal Care]"),导致匹配失败。
  2. 使用严格相等(===)只能匹配单个值,无法处理多选中项的场景。

情况1:保留完整产品类型对象

如果需要保留包含 businessGroup 和 category 的完整对象,使用以下代码:

getProductType(bigcChange = false) {
    try {
      const selectedGroups = this.makeLineForm.controls['businessGroup'].value;
      // 统一转为数组格式,兼容单选/多选返回值差异
      const normalizedGroups = Array.isArray(selectedGroups) 
        ? selectedGroups 
        : (selectedGroups ? [selectedGroups] : []);
      // 转为小写实现大小写不敏感匹配
      const lowerSelectedGroups = normalizedGroups.map(group => group.toLowerCase());

      if (lowerSelectedGroups.length > 0) {       
        this.productTypes = this.productResp.productTypes.filter(type => 
          lowerSelectedGroups.includes(type.businessGroup.toLowerCase())
        );        
      } else {
        // 未选中任何选项时清空结果
        this.productTypes = [];
      }
    } catch (error) {
      console.log('error', error);
    }
  }

情况2:仅返回分类名称数组

如果只需要提取分类名称(如示例中的 ["Laundry", "Skin Cleansing"]),在过滤后添加 map 操作:

getProductType(bigcChange = false) {
    try {
      const selectedGroups = this.makeLineForm.controls['businessGroup'].value;
      const normalizedGroups = Array.isArray(selectedGroups) 
        ? selectedGroups 
        : (selectedGroups ? [selectedGroups] : []);
      const lowerSelectedGroups = normalizedGroups.map(group => group.toLowerCase());

      if (lowerSelectedGroups.length > 0) {       
        this.productTypes = this.productResp.productTypes
          .filter(type => lowerSelectedGroups.includes(type.businessGroup.toLowerCase()))
          .map(type => type.category); // 提取分类名称
      } else {
        this.productTypes = [];
      }
    } catch (error) {
      console.log('error', error);
    }
  }

关键修改点

  • 数组归一化:将选中值统一转为数组,兼容部分组件单选时返回单个字符串的情况。
  • 大小写不敏感匹配:将选中组和数据中的组名转为小写,避免大小写差异导致匹配失败。
  • 多值匹配:使用 includes() 替代严格相等,判断当前产品类型的业务组是否在选中列表中。
  • 空值处理:未选中任何选项时清空结果,避免残留旧数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:00:31