Home > Mobile >  Filter on object in array
Filter on object in array

Time:06-07

in an Angular project I'm trying to delete an object from an array, to do this in need to filter the array and then replace that array into the storage (in this case capacitor/storage)

my function:

deleteArticle(id: string): void {
this.order = this.order[0].filter(p => p.products.productKey !== id);

}

order: Order; ==>

export interface OrderProduct {
  productKey: string;
  productName: string;
  price: number;
}
export interface Order {
  key?: string;
  customerKey: string;
  products: OrderProduct[];
  country?: string;
  city?: string;
  postcode?: string;
  addressLine?: string;
  creationDate?: any; //date
}

in HTML the on click:

<ion-col>
    <ion-button (click)="deleteArticle(p.productKey)">
      <ion-icon name="trash-outline"></ion-icon>
    </ion-button>
  </ion-col>

When clicking on the button, I can see the array is like expect it to be, same as the ID where I want to filter on, but I keep on getting this error:

Cannot read properties of undefined (reading 'filter')

image of console showing error

CodePudding user response:

If order is of type Order as you write and you try this.order[0].filter... you try to access a property named '0' (as in 'zero') of this.order, which most likely is undefined and thus has no filter method. from what I see you can remove the '[0]' and it could work. without more code just a guess tho.

CodePudding user response:

i've found the solution, it was a data type thing :)

needed to add products to this.order...

async deleteArticle(id: string): Promise<void> {
    this.order.products = this.order.products.filter(p => p.productKey !== id);
  }
  • Related