Jay
Jay

Reputation: 406

Array findIndex() function - Cannot read property 'id' of undefined

I am trying to implement addtoCart function in Angular2. I am using typescript class to represent a LineItem which is to represent product along with quantity and total price ( quantity * product price).

export interface Product {
  id?: number;
  name?: string;
  price?: number;
}

Line items:

export class LineItem {
  product: Product;
  quantity: number;
  totalPrice: number;
}

Array of Line items:

lineItems: LineItem[];

In add to cart function, I want to check if the item is already added, if so just find the line item corresponding the product and update that specific line item.

Method I am choosing is: - find the index. - if it is >-1 then add the new line item. - else edit the line item.

Issue is: When I am trying to find the index it shows this error

Cannot read property 'id' of undefined

code is :

  addProductToCart(product: any, quantity: number) {
    const lineItem: LineItem = Object.assign({}, product);
    lineItem.quantity = quantity;
    lineItem.totalPrice = product.price * quantity;
    const index = this.lineItems.findIndex( (item) => {
       return item.product.id === product.id
    });
    if(index > -1) {
      // edit the current item .
      this.lineItems[index].quantity = quantity;
      this.lineItems[index].totalPrice = quantity * product.price;

    }else {
      this.lineItems.push(lineItem);
    }
  }

no error on first call, second call throws error. this is the problem line:

  const index = this.lineItems.findIndex( (item) => {
       return item.product.id === product.id
    });

item.product.id throws : Cannot read property 'id' of undefined.

is it something with typescript class or interface or any logical error.

Upvotes: 2

Views: 2776

Answers (1)

Vikas Mahajan
Vikas Mahajan

Reputation: 355

const lineItem: LineItem = Object.assign({}, product);

This line result as a plain object :

lineItem = {ProductID: 1, ProductName: "Chai", UnitPrice: 18, quantity: 2}

So there is no item.product.id object chain its simple plain object

PLUNKER

Upvotes: -1

Related Questions