What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the cart. While I understand that an array is just a reference pointing to the product object, I need a solution to prevent this overwriting problem. Below is a snippet of how my code structure appears:

component.ts

this.cartService.add(product); // <- The Product contains key modifier: ["abc","def"]

cartService.ts

add(product) {
   product.qty = 1;
   product.total = product.price;
   this.cart.push(product);
}

Each time I push a product with a different modifier key (e.g., modifier: ["dfg", "gght"]), it overrides the values of all modifier keys in the existing this.cart array objects. When I log the two products in this.cart array:

(2) [{…}, {…}]
0:
category: "-M9JfAlqr_JiAiPTugc5"
description: "zxfsfsafas afa fsaff fsf safsa sfaf safs afsafa fas asf safs af aasf asfa asf ."
isAvail: true
key: "-MMWt2wDMVaHqj45eKFg"
modifiers: ["-MLxJCw0s0uDYSXYokz1"]
name: "Single Modifier"
price: 23
qty: 1
selectedModifiers: ["Corn"]  // <- Initially empty but gets populated after adding second product
total: 23
__proto__: Object

1:
category: "-M9JfAlqr_JiAiPTugc5"
description: "zxfsfsafas afa fsaff fsf safsa sfaf safs afsafa fas asf safs af aasf asfa asf ."
isAvail: true
key: "-MMWt2wDMVaHqj45eKFg"
modifiers: ["-MLxJCw0s0uDYSXYokz1"]
name: "Single Modifier"
price: 23
qty: 1
selectedModifiers: ["Corn"] 
total: 23
__proto__: Object
length: 2
__proto__: Array(0)

I am seeking advice on the optimal way to resolve this issue. Any ideas?

Answer №1

Always remember to create a copy of the product object before making changes

   addToCart(product) {
       const copiedProduct = {...product} 
       copiedProduct.quantity = 1;
       copiedProduct.totalPrice = copiedProduct.price;
       this.shoppingCart.push(copiedProduct);
    }

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

Converting Background Images from html styling to Next.js

<div className="readyContent" style="background-image: url(assets/images/banner/banner-new.png);"> <div className="row w-100 align-items-center"> <div className="col-md-7 dFlex-center"> ...

Unable to show the name of the chosen file

After customizing the input [type = file], I successfully transformed it into a button with a vibrant green background. Here is the code snippet that enabled this transformation: <style> #file { height:0px; opacity:0; } ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Enhance the input by incorporating more fields without altering the existing content

Currently, I am working on creating an input form that includes multiple fields and has the capability to generate a preview of the entered content in a separate div. One key feature I would like to implement is allowing users to add additional fields as n ...

Host several Node.js applications concurrently on one server

Attempting to run multiple Node.js apps on a single server has been my focus lately. I have been exploring solutions for similar queries here and have reached some progress. Let's consider the scenario where I have two apps, each serving different HTM ...

Ways to display additional text with a "Read More" link after three lines of content without relying on a

I am currently working on an application where I need to display text in a limited space of 3 lines. If the text exceeds this limit, I want to show either "Read More" or "Hide". Below is the code snippet that I am using for this functionality. class Cust ...

Preventing access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

Encountering browser freezing issues with a Next.JS app when trying to add an input field

I am currently utilizing Next.JS to construct a form with two inputs. I have followed the traditional React approach for input text reading and validation. "use client" import { firebaseApp } from '@/app/firebase'; import React, { useCa ...

Is it possible to choose the inverse of a user-defined type in Angular?

Is it possible to retrieve the opposite of a specified custom type within a variable using Typescript? For example, if I define a type like this: type Result = 'table' | 'grid'; Then any variable with the type Result can only be assign ...

Keeping state between navigations in Ionic and AngularJS: A guide

In the process of developing my very first hybrid mobile application using Ionic and AngularJS, I have encountered a challenge that I am currently trying to resolve. The issue at hand involves maintaining the state of the graphical user interface between n ...

Order all elements except the initial one using the quicksort algorithm in C

I have a unique challenge at hand. My task involves sorting an array of elements based on color on a chess board. The process is straightforward, as outlined in the attached code: if x%2==y%2, the element is black; if not, it's white. However, there i ...

Manipulating specific elements within a MongoDB document's array using index values in a Node.js environment

Is there a way to increase the value of a specific element in an array within a MongoDB document using Meteor or nodeJS? For example, consider the following document: { "_id" : "4tP6ewe4Z5kwYA3Je", "name" : "chutia", "address" : "shonir akhra ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Is it possible to leverage ES6 modules within a Node.js application while also debugging it using Visual Studio?

Trying to create a basic node.js module test project using ES6 in Visual Studio 2015 has resulted in build errors, preventing me from running or debugging the application. Could it be that I arrived at the party too soon? I attempted opening and building ...

Obtaining numerical values from a string with the help of Selenium IDE

I've gone through numerous solutions for this issue and attempted all of them, but none seem to be effective. Despite its seemingly simple nature, I am struggling with the following task; My objective is to extract a numerical value from a string and ...

Avoiding redundant code in React Components: Best practices to keep your code DRY

I am currently utilizing React with Material UI v1.0 to implement a list, but I want to avoid code repetition. Here is the existing code: import List from 'material-ui/List'; import DashboardIcon from 'material-ui-icons/Dashboard'; ...

Having trouble posting data in node.js using MongoDB and EJS

Hey everyone, I'm currently working on creating a page with a form and text input fields. However, I'm encountering an error that says "Cannot Post". Here is my code, any help would be greatly appreciated. Why isn't it working? This is app. ...

"The powerful trio of Moongose, expressjs, and node-webkit combine forces

I'm currently in the process of developing an app using node-webkit, with expressjs and mongoose as the foundation. As a newcomer to this technology stack, I've encountered some challenges. One specific issue involves my attempt to integrate a m ...

Trouble with Component Lifecycle (ComponentDidMount) activation while switching tabs in TabBar?

After implementing the react-native-tab-navigator library to navigate between components, I encountered an issue where the componentDidMount lifecycle method works only once. I have reached out for help by posting a query on Github and have also attempted ...