I need help filtering an array of objects based on user input. The challenge I'm facing is that the object structure includes both a name and a value, unlike a simple string array. How can I modify the existing code (which currently works for a string array) to work with an array of objects?
HTML
<input type="text" placeholder="{{ 'string' | translate }}*" matInput formControlName="example" [matAutocomplete]="exampleAutoComplete" (keyup)="filterExample($event)">
<mat-autocomplete #exampleAutoComplete="matAutocomplete" [displayWith]="displayExample">
<mat-option *ngFor="let example of exampleArray" [value]="example.id">
{{example.name | titlecase }}
</mat-option>
</mat-autocomplete>
<mat-error *ngIf="companyInfoFormGroup.get('example').invalid">
<ng-container *ngIf="companyInfoFormGroup.get('example').errors.required">
string
</ng-container>
<ng-container *ngIf="companyInfoFormGroup.get('example').errors.example">
string
</ng-container>
<ng-container *ngIf="companyInfoFormGroup.get('example').errors.maxlength">
string
</ng-container>
</mat-error>
</mat-form-field>
TYPESCRIPT
displayExample = (id: string): string => {
if (!id) {
return '';
}
this.exampleName = this.exampleArray.find((item: { id: string, name: string }) => {
return item.id === id;
}).name;
return this.exampleName;
}
public filteredExamples(event): void {
this.filteredExampleNames = this.filteredExampleNames
.filter((example: string) => example.toLowerCase().includes(event.target.value.toLowerCase()));
}
I am aware that the current filter method is suitable for a string[], but I need guidance on adapting it for an array of objects.
OBJECT
{
"id": "f0493847-f05e-ea11-a811-342cd25c7c6",
"name": "example 1"
}