forEach is not a function error

this.cart = this.aggregateCart(‘cart’);

aggregateCart = (cart) => {
let newCart = ;
cart.forEach(function(item) {
if(newCart.indexOf(item) < 0) {
return newCart;
i have initialized this in constructor and i intend to use this function to aggregate my cart elements but the error is shown like this “”


When you call to this.aggregateCart('cart'), the cart parameter you’re passing to the function is a string, and as such, it doesn’t implement the forEach() method like arrays and other iterable objects do. That’s why “cart.forEach is not a function”, because forEach is undefined.

I hope it helps,

1 Like

thank you @ FdezRomero i undrestand what you conveyed without this function the items which i push into the cart not only gets updated on quantity but also a new item gets pushed into the cart with updated quantity

the cart component code

<ion-item-sliding *ngFor=“let product of cart; let productId = index” #index>

    <ion-item >
      <ion-thumbnail item-start>
        <img src="{{product.img}}">
      <h3 class="name">{{}}</h3>
      <div clear item-end>
        <div clear item-end>
          Quantity: {{product.quantity}} ({{product.quantity * product.price}}$)

      <ion-item-options side="right">
        <button ion-button color=default class="productsModification" (click)="addOne(productId)">
          <ion-icon name="add"></ion-icon>
        <button ion-button color="danger" class="productsModification" (click)="removeOne(productId)">
          <ion-icon name="remove"></ion-icon>

      <ion-item-options side="left" (click)="deleteProduct(productId)">
        <button ion-button>Delete</button>

the typescript code

addToCart = (catId, productId) => {[catId].products[productId].quantity =[catId].products[productId].quantity?[catId].products[productId].quantity + 1

: 1;



thank you

I understand that there’s more code. But the aggregateCart function you pasted in the first post is wrong, because inside of this context, cart is a string and not an array.

thank you@ FdezRomero thats why i asked you sir that if there are any alternate ways to achieve my task

Oh, I didn’t understand you were asking for alternatives. I’m sorry but that’s kind of a broad question and there are many different ways to code it depending on your needs.

addToCart = (catId, productId) => {[catId].products[productId].quantity =[catId].products[productId].quantity

?[catId].products[productId].quantity + 1
: 1;


could you help me with this every time i add an item to cart not only the quantity gets updated but also same item gets pushed once again