【问题标题】:Angular filter array inside array数组内的角度过滤器数组
【发布时间】:2021-04-01 13:42:50
【问题描述】:

我正在使用 Angular 9 应用程序,我需要根据每个对象内的另一个数组过滤一个数组。为了理解我这里是一个数组的例子

const products = [
  {
      name: 'Product 1',
      origins: [
          { quantity: 1, name: 'Pack 1' },
          { quantity: 1, name: 'Pack 2' },
      ]
  },
  {
      name: 'Product 2',
      origins: [
          { quantity: 1, name: 'Pack 1' },
          { quantity: 1, name: 'Pack 2' },
      ]
  },
  {
     name: 'Product 3',
     origins: [
          { quantity: 1, name: 'Inventory' },
          { quantity: 1, name: 'Pack 5' },
     ]
  }
]

所以我得到了一个过滤器输入,它必须通过产品名称或一个或多个原产地名称的巧合来过滤产品。

例如,如果我输入“2”,结果数组必须是:

products = [
  {
      name: 'Product 1',
      origins: [
          { quantity: 1, name: 'Pack 2' },
      ]
  },
  {
      name: 'Product 2',
      origins: [
          { quantity: 1, name: 'Pack 2' },
      ]
  }
]

因为字符“2”出现在产品 1 和产品 2 的原产地名称中,也出现在名称“产品 2”中 我尝试了很多方法来做到这一点,但是当我将它放入管道时,结果数组总是会修改我的原始数组

<input type="text" [(ngModel)]="searchtext">
<div *ngFor="let p of (saleProducts | filter : searchtext); let i = index">
    {{ p.name }}
    <div *ngIf="p.origins.length > 0">
        <div *ngFor="let o of p.origins">
            {{ o.name }}
        </div>
    </div>
</div>

在不修改原始数组的情况下使用管道进行过滤的最佳(简单和优化)方法是什么?

【问题讨论】:

    标签: arrays angular typescript filter


    【解决方案1】:

    在管道实现下使用默认键origins

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
    
      transform(value: any[], searchName: string, key = 'origins'): any[] {
        const products = []
        value.forEach(product => {
          const matches = product[key].filter(({ name }) => name === searchName)
          if (matches.length) {
            products.push({ ...product, [key]: matches })
           }
        })
      
        return products
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-29
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多