I am currently developing an e-commerce app with a front-end built using Angular 13.
The following code snippet is designed to calculate the total price of items in the shopping cart:
import { Component, OnInit } from '@angular/core';
@Component({
selector: '.app-top-cart',
templateUrl: './top-cart.component.html',
styleUrls: ['./top-cart.component.css']
})
export class TopCartComponent implements OnInit {
cartItems: any = [
{
id: 1,
title: "iPhone 9",
description: "An apple mobile which is nothing like apple",
price: 549,
discountPercentage: 12.96,
rating: 4.69,
stock: 94,
brand: "Apple",
category: "smartphones",
thumbnail: "https://dummyjson.com/image/i/products/1/thumbnail.jpg",
images: [
"https://dummyjson.com/image/i/products/1/1.jpg",
"https://dummyjson.com/image/i/products/1/2.jpg",
]
},
{
id: 2,
title: "iPhone X",
description: "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
price: 899,
discountPercentage: 17.94,
rating: 4.44,
stock: 34,
brand: "Apple",
category: "smartphones",
thumbnail: "https://dummyjson.com/image/i/products/2/thumbnail.jpg",
images: [
"https://dummyjson.com/image/i/products/2/1.jpg",
"https://dummyjson.com/image/i/products/2/2.jpg",
]
},
{
id: 3,
title: "Samsung Universe 9",
description: "Samsung's new variant which goes beyond Galaxy to the Universe",
price: 1248,
discountPercentage: 15.46,
rating: 4.09,
stock: 36,
brand: "Samsung",
category: "smartphones",
thumbnail: "https://dummyjson.com/image/i/products/3/thumbnail.jpg",
images: [
"https://dummyjson.com/image/i/products/3/1.jpg"
]
},
];
constructor() { }
totalPrice: number = 0;
doTotalPrice(){
let total = 0;
this.cartItems.forEach((item: { price: number, quantity: number }) => {
item.quantity = 1;
total += item.price * item.quantity
});
this.totalPrice = total;
}
ngOnInit(): void {
this.doTotalPrice();
}
}
The Objective
Every time a new item is added to the cartItems
array, if the item already exists in the array, I want to update the quantity instead of creating a duplicate entry.
Access the Code on Stackblitz
You can view the complete code HERE.
The Predicament
I am struggling to figure out how to update the item.quantity
when a product is added to the cart more than once.