简体   繁体   中英

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. 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

 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;

<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.

I am just learning angular/JavaScript/TypeScript. I will appreciate if any one can help.

your pipe not returning anything... you need to return data from the pipe .

check this stackblitz project or below code

  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;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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