Home > Back-end >  Iterating thorugh array but always returning last value
Iterating thorugh array but always returning last value

Time:07-07

I am iterating thorugh an array and trying to get different data for each object in array but I end up with same data, if i have three products in billBodies i end up with three item that have the same value (for example i have 3 candies, 2 coffees, and 4 candy bars result I get is 4 candy, 4 candy, 4 candy). Hope anyone can help i tried to search similar problems but didn't find it though...

 for (let bill of dataOfBillHeader.billBodies) {
        console.log(dataOfBillHeader)
        console.log(this.productToShowOnView)
      
        
        this.productToShowOnView.cipher = bill.product.cipher;
        this.productToShowOnView.name = bill.product.name;
        this.productToShowOnView.measure = bill.product.measure;
        this.productToShowOnView.count = bill.product.count;
        this.productToShowOnView.price = bill.product.price;
        this.productToShowOnView.id = dataOfBillHeader.id;
        this.productToShowOnView.count = bill.count;
        this.productToShowOnView.quantity = bill.quantity;
        this.productToShowOnView.discount = bill.discount;
        this.productToShowOnView.discountAmount = bill.discountAmount;
        this.productToShowOnView.totalPrice = bill.totalPrice;
        console.log("to show on view is "   JSON.stringify(this.productToShowOnView));
        
        const newBasket = this.productsInBasket;
        this.productsInBasket.push(this.productToShowOnView);
        this.productsInBasket = [...newBasket];
        this.cd.detectChanges();
      }

CodePudding user response:

Well, you are just pushing the same object (reference) in there over and over, namely this.productToShowOnView. Why are you using this.productToShowOnView? Why not a local constant. And with a little magic you can make it a bit smaller, although I don't understand why you would go from one product data format to another one...:

const newBasket = [...this.productsInBasket];

for (let bill of dataOfBillHeader.billBodies) {
  const product = { 
    // no need to get all those individually
    ...bill.product,
    ...bill,
    //this is weird, all products have the same id?
    id: dataOfBillHeader.id,
  };

  newBasket.push(product);
}

this.productsInBasket = newBasket;
this.cd.detectChanges();
  • Related