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

未知对象属性时,如何用对象数组过滤目标对象数组?

通用对象数组过滤实现方案

需求概述

需要实现一个通用的对象数组过滤函数,满足以下要求:

  • 过滤条件支持单个对象或对象数组两种格式
  • 若过滤条件包含目标数组元素中完全不存在的属性,直接返回空数组
  • 适配任意数量的过滤规则,只要元素满足所有过滤条件即可保留

实现思路

  1. 统一条件格式:将单个对象格式的过滤条件转为数组,方便统一遍历处理
  2. 合法性校验:收集所有过滤条件的属性,检查这些属性是否在目标数组的至少一个元素中存在;若有属性完全不存在于数组元素中,返回空数组
  3. 执行过滤:遍历目标数组,仅保留满足所有过滤条件的元素(每个过滤条件的所有键值对都需匹配)

代码实现

function filterArray(myArray, myFilter) {
  // 处理空数组情况
  if (!myArray.length) return [];

  // 统一过滤条件为数组格式
  const filterConditions = Array.isArray(myFilter) ? myFilter : [myFilter];

  // 收集所有过滤条件中的属性
  const filterProps = new Set();
  filterConditions.forEach(cond => Object.keys(cond).forEach(key => filterProps.add(key)));

  // 检查是否存在无效属性(数组中无任何元素拥有该属性)
  const hasInvalidProp = [...filterProps].some(prop => {
    return !myArray.some(item => Object.prototype.hasOwnProperty.call(item, prop));
  });
  if (hasInvalidProp) {
    return [];
  }

  // 执行过滤:元素需满足所有过滤条件的所有键值对
  return myArray.filter(item => {
    return filterConditions.every(cond => {
      return Object.entries(cond).every(([key, value]) => {
        return item[key] === value;
      });
    });
  });
}

测试验证

测试数据

const myArray = [
  { id: "100", area: "01", country: "AT"},
  { id: "101", area: "02", country: "DE"}, 
  { id: "102", area: "01", country: "DE"},
  { id: "103", area: "03", country: "CH"},
  { id: "104", area: "01", country: "AT"}
];

示例1:单个对象过滤条件

const filter1 = { area: "01", country: "AT" };
console.log(filterArray(myArray, filter1));
// 输出:[{ id: "100", area: "01", country: "AT"}, { id: "104", area: "01", country: "AT"}]

示例2:数组格式过滤条件

const filter2 = [ {area: "01"} ];
console.log(filterArray(myArray, filter2));
// 输出:[{ id: "100", area: "01", country: "AT"}, { id: "102", area: "01", country: "DE"}, { id: "104", area: "01", country: "AT"}]

示例3:含无效属性的过滤条件

const filter3 = { name: "test" };
console.log(filterArray(myArray, filter3));
// 输出:[]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:27:38