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

AngularJS filter过滤器排除选项:指定属性过滤JSON数组实现

实现AngularJS带属性范围/排除的Filter过滤器

嘿,这个需求我之前在做AngularJS项目时刚好实现过!内置的filter确实会默认遍历对象的所有属性进行匹配,要实现指定过滤范围或者排除特定属性的效果,最灵活的方式是自定义一个过滤器,完全掌控匹配逻辑。下面分两种场景给你具体实现方案:

一、指定仅在特定属性中过滤

如果明确知道要在哪些属性里搜索,可以写一个只检查指定属性的过滤器:

自定义过滤器代码

// 假设你的Angular模块是app,替换成你自己的模块名
angular.module('app').filter('filterByAllowedProps', function() {
  // 辅助函数:支持获取嵌套属性(比如y.sub)
  function getNestedValue(obj, propPath) {
    return propPath.split('.').reduce((current, key) => current?.[key], obj);
  }

  return function(items, searchTerm, allowedProps) {
    // 无搜索关键词时直接返回原数组
    if (!searchTerm) return [...items];
    
    const lowerSearchTerm = searchTerm.toLowerCase();
    return items.filter(item => {
      // 只要有一个允许的属性匹配,就保留该对象
      return allowedProps.some(prop => {
        const value = getNestedValue(item, prop);
        // 处理非字符串类型的属性值,转成字符串后再匹配
        return value?.toString().toLowerCase().includes(lowerSearchTerm);
      });
    });
  };
});

使用方式

比如你想仅在prop1和e这两个属性中搜索"some string",就这么调用:

var filteredData = $filter('filterByAllowedProps')($scope.data, "some string", ['prop1', 'e']);

如果需要匹配嵌套属性(比如第二个对象的y.sub),直接把属性路径传进去就行:

// 搜索y.sub属性中包含"2"的对象
var filteredNested = $filter('filterByAllowedProps')($scope.data, "2", ['y.sub']);

二、排除特定属性后过滤

如果需要排除某些属性(比如不想匹配name字段),可以写一个跳过指定属性的过滤器:

自定义过滤器代码

angular.module('app').filter('filterExcludeProps', function() {
  // 辅助函数:支持获取嵌套属性
  function getNestedValue(obj, propPath) {
    return propPath.split('.').reduce((current, key) => current?.[key], obj);
  }

  return function(items, searchTerm, excludedProps) {
    if (!searchTerm) return [...items];
    
    const lowerSearchTerm = searchTerm.toLowerCase();
    excludedProps = excludedProps || [];
    
    return items.filter(item => {
      // 遍历对象所有可枚举属性
      for (const prop in item) {
        // 如果当前属性不在排除列表中,就检查是否匹配
        if (!excludedProps.includes(prop)) {
          const value = getNestedValue(item, prop);
          if (value?.toString().toLowerCase().includes(lowerSearchTerm)) {
            return true;
          }
        }
      }
      return false;
    });
  };
});

使用方式

比如你想排除name属性,搜索其他属性中的"some string":

var filteredData = $filter('filterExcludeProps')($scope.data, "some string", ['name']);

额外优化点

  • 如果需要精确匹配,可以把includes换成===,同时注意值的类型转换;
  • 如果不需要大小写不敏感,去掉toLowerCase()即可;
  • 可以给过滤器加默认参数,比如默认允许所有属性/排除空数组,提升易用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:51:34