Currently, I am developing a project in Angular 9 and I have encountered a challenge regarding filtering an array based on another nested array within each object. To illustrate my issue, here is a sample of the array:
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' },
]
}
]
I need to implement a filter functionality that can search for matches based on the product name or any origin's name.
For instance, if the user types "2", the filtered array should look like this:
products = [
{
name: 'Product 1',
origins: [
{ quantity: 1, name: 'Pack 2' },
]
},
{
name: 'Product 2',
origins: [
{ quantity: 1, name: 'Pack 2' },
]
}
]
This outcome demonstrates how the character "2" appears in both the name of the origins and the product itself (e.g., Product 1 and Product 2).
I have attempted various strategies to achieve this without modifying the original array, especially when implementing it within a pipe.
<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>
What would be the most efficient and straightforward approach to create a non-destructive filtering mechanism using a pipe in this scenario?