You need to enable JavaScript to run this app. Vue+Typescript如何按选中属性列表过滤含布尔值的对象数组
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Typescript如何按选中属性列表过滤含布尔值的对象数组

嵌套布尔属性多条件AND过滤实现方案

实现思路

  • 先将所有维度的过滤条件整合为统一的配置对象,便于后续扩展新的过滤维度
  • 遍历源数组的每一项,对每个过滤维度做校验:该维度下所有勾选的属性对应值都为true时,才符合该维度要求
  • 所有维度校验都通过的项,才会被保留到结果集中

代码实现

示例数据与过滤条件

// 待过滤的数据源
const dataList = [
  {
    id: 1,
    characteristic1: {
      prop1: true,
      prop2: true,
      prop3: false
    },
    characteristic2: {
      prop4: true,
      prop5: false
    }
  },
  {
    id: 2,
    characteristic1: {
      prop1: true,
      prop2: false,
      prop3: true
    },
    characteristic2: {
      prop4: true,
      prop5: true
    }
  }
]

// 过滤条件:key对应嵌套对象的属性名,value为勾选的属性数组
const filterConditions = {
  characteristic1: ["prop1", "prop3"],
  characteristic2: ["prop4"]
}

过滤函数

function filterDataList(dataList, filterConditions) {
  return dataList.filter(item => {
    // 所有过滤维度全部满足才保留
    return Object.entries(filterConditions).every(([charKey, requiredProps]) => {
      // 对应维度没有勾选任何属性时,跳过该维度的校验
      if (requiredProps.length === 0) return true
      // 该维度下所有勾选的属性值都为true才符合要求
      return requiredProps.every(prop => item[charKey]?.[prop] === true)
    })
  })
}

调用示例

const filteredResult = filterDataList(dataList, filterConditions)
console.log(filteredResult)
// 输出结果为id=2的项:id=1的characteristic1.prop3为false,不符合第一个维度的要求,被过滤

特性说明

  • 天然适配AND逻辑:用Array.every实现,只有所有校验条件都通过才会保留项
  • 边界兼容:加入可选链?.避免数据缺失对应属性时报错
  • 扩展性强:新增过滤维度只需要在filterConditions中新增对应配置即可,不需要修改过滤逻辑
  • 适配常规交互:单个维度勾选数组为空时,自动跳过该维度的过滤,符合复选框全不选时不限制该维度的常规产品逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 08:15:05