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

Angular管道中如何过滤嵌套数组,保留匹配的组与子项?

嵌套数组过滤实现(Angular管道场景)

需求

实现嵌套结构的数组过滤,满足:

  • 搜索「Nest Name 3」时,仅返回Group B及其中的Nest Name 3
  • 搜索「2」时,仅返回Group B及其第一个嵌套对象

数据源

items = [
    {
        "key": "Group A",
        "value": [
            {
              "name": "Nest Name 1"
            }
        ]
    },
    {
        "key": "Group B",
        "value": [
            {
              "name": "Nest Name 2"
            },
            {
              "name": "Nest Name 3"
            }
        ]
    }
];

现有问题

当前尝试的过滤代码仅能返回匹配的组,但组内未匹配的子项未被移除:

var tempList = [];
items.filter(group => group.value.filter(item => searchText.split(' ').every(q => new RegExp(q, 'i').test(item[field])))).forEach(product => tempList.push(product));
return tempList;

解决方案

要同时过滤组和组内子项,需在保留匹配组的同时,对组的value数组做过滤,且避免修改原数组。以下是Angular管道的实现代码:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'nestedFilter' })
export class NestedFilterPipe implements PipeTransform {
  transform(items: any[], searchText: string, field: string): any[] {
    if (!items || !searchText) return items;

    const searchQueries = searchText.split(' ');
    const matches = (item: any) => searchQueries.every(q => new RegExp(q, 'i').test(item[field]));

    return items.reduce((filteredGroups, group) => {
      const filteredItems = group.value.filter(matches);
      if (filteredItems.length) {
        filteredGroups.push({
          ...group,
          value: filteredItems
        });
      }
      return filteredGroups;
    }, []);
  }
}

逻辑说明

  1. 拆分搜索关键词为查询数组,定义通用匹配函数matches,统一处理子项匹配逻辑
  2. 使用reduce遍历原数组,对每个组的value执行过滤
  3. 仅当组内存在匹配子项时,将**复制后的组(替换为过滤后的子项数组)**加入结果集
  4. 通过扩展运算符...group复制原组属性,避免修改原始数据源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:46:00