简体   繁体   English

如何在 angular 中创建 pipe 以过滤具有嵌入式数组的对象数组

[英]How to create a pipe in angular to filter array of objects with embedded array

Please, I have an array of object which embeds another array.拜托,我有一个嵌入另一个数组的 object 数组。 I want to display with just a card that contains the item(s) filtered.我只想显示一张包含已过滤项目的卡片。 Please check my illustration below.请检查我下面的插图。 Thank you谢谢

const customerList = [
    {
      id: 1,
      customer: 'Rachel Stone',
      items: ['Sardines', 'Milk', 'Custard', 'Egg']
    },
    {
      id: 2,
      customer: 'John Bull',
      items: ['Vegetable Oil', 'Bread','Egg']
    },
    {
      id: 3,
      customer: 'Tega Paul',
      items: ['sugar', 'milk', 'butter']
    },
 
  ]

I created the filter in a pipe我在 pipe 中创建了过滤器

 transform(list: any[], filterText: string): any {
 return list.map(x => {
   x.items ? x.items.filter((item: string) => item.search(new RegExp(filterText, 'i')) > -1) : [];
   })
}

I used the pipe here as follows;我在这里使用的pipe如下;

<div *ngFor="let order of orders | searchFilter: searchTerm ">
                    <app-item-card 
                    [customer]="order.customer" 
                    [items]="order.items"
                    >
                    </app-item-card>
                    <button >
                        Order
                    </button>
                </div>

The items card物品卡

    <div>
      <div> {{ customer }}</div>
      <div >
        <ul>
           <li  *ngFor="let item of items">{{ item }}</li>
        </ul>
      </div>
    </div>

It was blank.它是空白的。 All I want to do is if I type custard , it should display only a card where custard appears.我想要做的就是如果我输入custard ,它应该只显示出现 custard 的卡片。

I am just learning angular/JavaScript/TypeScript.我只是在学习 angular/JavaScript/TypeScript。 I will appreciate if any one can help.如果有人可以提供帮助,我将不胜感激。

your pipe not returning anything... you need to return data from the pipe .你的pipe没有返回任何东西......你需要从pipe返回数据。

check this stackblitz project or below code 检查这个 stackblitz 项目或下面的代码

  transform(list: any[], filterText: string): any {
    if (filterText) {
      return list.map((x) => {
        return x.items
          ? {
              items: x.items.filter((item: any) =>
                item.toLowerCase().includes(filterText.toLowerCase())
              ),
              customer: x.customer,
            }
          : { items: [], customer: x.customer };
      });
    } else {
      return list;
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM