What is the best way to modify the quantity property of a cart item object within the framework of this Angular 13 online shopping application?

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.

Any suggestions on how to manage the quantity count?

Answer №1

If you want to keep track of items in a "basket", one approach is to create a Map where the item ID serves as the key.

When adding an item to the basket, first check if it already exists in the map. If not, add the item to the map with a quantity of 1. If it does exist, simply increase the quantity.

Another option is to use an array to store the items and then count the occurrences in the array at the end.

Answer №2

Try a different approach by organizing available items and cart items into separate arrays. This method may provide a clearer understanding for you.


itemsAvailable = [{
  id: 1,
  title: 'iPhone 9',
  // ...
}];

itemsInCart = [];

// ...

addToCart(item) {
  this.itemsInCart.push(item);
}

// ...

get totalCost() {
  return this.itemsInCart.reduce((total, { price }) => total + price, 0);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

"Code snippets customized for React are not functioning properly in the javascriptreact.json file within Visual Studio Code

I'm looking to incorporate some customized React.js code snippets into my Visual Studio Code setup. I am aware of the two files in VSCode that handle this - javascript.json and javascriptreact.json. Although the snippets work well in javascript.json, ...

VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component: ... <v-stepper-step :rules="[()=>isValid(1)]" > MyStep </v-stepper-step> <v-stepper-content> <Mytag ref="MyReference" /> </v-stepper-content> ... methods: { isValid(number){ ...

Inquiring about how to make the pieces move on the checker boards I created

I'm having trouble getting my SVG pieces to move on the checkerboard. Can someone please help me figure out how to make them move, even if it's not a valid move? I just want to see them in motion! The important thing is that the pieces stay withi ...

Enumerate the variable values that are validated using jQuery

I've made good progress with this in jsFiddle, but I can't seem to figure out why the first value isn't displaying a bullet point.. Check out my code on jsFiddle! <div id="checkboxes"> <input id="chkbx_0" type="checkbox" name= ...

Utilizing the URL path name for data retrieval in Next.js 14 - A step-by-step guide

I'm currently developing a blog using AWS Amplify Gen 2 and GraphQL for a Next.js 14 project with TypeScript. As part of my application, I need to fetch specific data based on the URL path name. Here's how I've approached it: My approach in ...

Issue encountered: Exceeded maximum call stack size while running npm start command for Angular

Encountering the 'Error: Maximum call stack size exceeded' while running ng serve Node version: v14.17.5 Npm version: 6.14.14 "dependencies": { "@angular-material-components/datetime-picker": "^5.1.0", " ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Utilizing Promises with Chained .then() Functions

I am struggling with simplifying the readability of my code. I have separated it into two main functions, but I am still dealing with nested .then() statements. I am looking for advice on how to structure these functions more effectively. It is important ...

ASP.Net & Ajax Fusion Login Interface

I am encountering an issue while creating a login page with HTML, AJAX, and ASP.NET. The data is being passed to the AJAX function successfully, but when I debug the ASP page, the username and password are showing up as NULL. The purpose of the code is to ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...

Guide to implementing Angular 2 lazy loading with the Visual Studio 2015 ASP.NET Core Template Pack

I am currently working on implementing router lazy loading in Angular 2. My goal is to be able to do something like this: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full', { path: 'about&apos ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...

The request.body in Express.js is currently undefined

const express = require('express'); const cors = require('cors'); const app = express(); app.use(express.json()) app.use(cors()); app.post('/', (req,res) => { console.log(req.body); res.send('received') ...

Error encountered: Unexpected token while trying to implement React + Node.js tutorial on a blog platform

I recently started following a tutorial on Site Point in an attempt to create my own React app. However, I hit a roadblock at these specific steps: mkdir public npm install npm run developement The first command failed for me because I already had a &a ...

Is there a way to prevent the Material UI Chip component from appearing when there is no content present?

I have developed an application that pulls content from an API and displays it on the screen. Within this app, I have implemented a Material UI Card component to showcase the retrieved information, along with a MUI Chip component nested within the card. &l ...

Having difficulty resolving sub-modules using webpack

Currently, I am trying to set up the @microsoft/signalr npm package with webpack by importing the module using import * as signalR from '@microsoft/signalr'. However, I encountered an error message indicating that webpack is unable to resolve the ...

Guide on How to Retrieve the Following YouTube Video using a PHP Array

I have a PHP/HTML script that currently loads a random YouTube video from an array every time the page is refreshed. However, I am looking to add functionality for next and previous buttons to allow users to cycle through the videos in the array. The goal ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

Vuejs Countdown Timer Powered by Moment.js

Currently, I am working on a vuejs page and I am looking to incorporate a countdown timer that counts down from 5 minutes (e.g. 5:00, 4:59, and so on). Although I have never used momentjs before, I have gone through the moment docs but I am finding it ch ...