Estoy iterando a través de una matriz y tratando de obtener datos diferentes para cada objeto en la matriz, pero termino con los mismos datos, si tengo tres productos en billBodies, termino con tres elementos que tienen el mismo valor (por ejemplo, tengo 3 dulces , 2 cafés y 4 golosinas, el resultado que obtengo es 4 golosinas, 4 golosinas, 4 golosinas). Espero que alguien pueda ayudar. Traté de buscar problemas similares pero no los encontré ...
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(); }Bueno, solo está presionando el mismo objeto (referencia) allí una y otra vez, a saber, this.productToShowOnView . ¿Por qué está usando this.productToShowOnView ? ¿Por qué no una constante local? Y con un poco de magia puedes hacerlo un poco más pequeño, aunque no entiendo por qué se pasa de un formato de datos de producto a otro...:
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();