My issue lies in the subtraction of a quantity by using Object X from Array 1 and Object Y from Array 2

I am facing an issue with the function I'm using. It seems that when I attempt to do subtraction, both arrays are getting subtracted instead of just one.

Here are the variables:

let data1 = [
  { ProductTotalId: 30, ProductId: 30, Quantity: 50 },
  { ProductTotalId: 31, ProductId: 29, Quantity: 20 },
  { ProductTotalId: 32, ProductId: 28, Quantity: 30 },
  { ProductTotalId: 33, ProductId: 27, Quantity: 30 },
];

let Remove = [
  { ProductTotalId: 30, ProductId: 30, Quantity: 2 },
  { ProductTotalId: 30, ProductId: 30, Quantity: 10 },
  { ProductTotalId: 31, ProductId: 29, Quantity: 3 },
  { ProductTotalId: 32, ProductId: 28, Quantity: 12 },
  { ProductTotalId: 32, ProductId: 28, Quantity: 2 },
  { ProductTotalId: 33, ProductId: 27, Quantity: 11 },
  { ProductTotalId: 33, ProductId: 27, Quantity: 5 },
]
let data2

This is the function being used:

data2 = data1;
for (let value of data2) {
  for (let data of Remove) {
    if (value.ProductId === data.ProductId) {
      value.Quantity = value.Quantity - data.Quantity;
    }
  }

}
console.log(data1);
console.log(data2);

The problem here is that 'data1' is equal to 'data2' with Quantity Subtracted. What I actually need is for 'data2' to be subtracted without any changes to 'data1'.

Link to Stackblitz: https://stackblitz.com/edit/typescript-u8mzii

Thank you for your attention.

Answer №1

Creating a reference for object by assigning data1 to data2 does not make a copy of the object <code>data1
. Any changes made to the reference data2 will also affect the object referenced by data1 (which is the same object).

To actually create a copy of the object, you can use the following method:

data2 = JSON.parse(JSON.stringify(data1));

Check out the DEMO here

Answer №2

The issue lies within the data structure you are using.

When you write data2 = data1;, it simply assigns a reference to the same array, not creating a new one.

For two separate arrays, you need to create a new array and populate it with the contents of the first array.

To achieve this, use the following code:

const data2 = Object.assign([], data1);

This will give you a duplicated copy of the original array.

Answer №3

To prevent any alterations in data2 from affecting data1, it is essential to duplicate data1 as data2. The method outlined below demonstrates how you can achieve this:

let data2 = JSON.parse(JSON.stringify(data1))

By first converting (JSON stringify) data1, and then parsing the result into data2, you ensure that they are identical but not the same.

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

Error: Unexpected token < occurs when using SVG require in Jest

I'm struggling to locate the source of this error. Currently, I am working with Typescript in React and using Jest and Enzyme for unit testing. Below is a snippet from my Package.json file: "scripts": { "start": "node server.js", "bundle": ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

PHP - transforming an array into a collection of unique values

I have a unique array structure that I need to optimize: array(43197) { [0]=> array(4) { ["id"]=> string(5) "10038" ["country"]=> string(7) "Andorra" ["city"]=> string(16) "Andorra la Vella" ["name"]=> string(25) "Andor ...

What steps can be taken for TypeScript to identify unsafe destructuring situations?

When working with TypeScript, it's important to prevent unsafe destructuring code that can lead to runtime errors. In the example below, trying to destructure undefined can cause a destructuring error. How can we ensure TypeScript does not compile suc ...

Show every item from a collection on individual lines within an Angular2 module

I am working with an Angular2 component that is responsible for displaying a list of speakers stored in some data. Currently, when I add the code below to my xyz.component.html, it shows the list as comma-separated strings. However, I would like each speak ...

Changing the color of a selected list element using an Angular directive

I'm currently facing an issue with my directive that is supposed to turn a list element red when clicked. It works fine, but I also want it to revert back to black when another list item is selected, so only one item stays in red color. Here is how I ...

"Dealing with duplicate values in an array when using ng-repeat in Angular

As I delve into the world of AngularJS, I find myself a bit perplexed by ng-repeat when working with arrays. Interestingly, the code below doesn't quite function as expected...but when I transform dayNames into an object with key-value pairs, it works ...

How to update a query with Codeigniter's active record by leveraging data stored in an array

I'm currently working with an array that contains two nested arrays - one storing item ids, and the other storing the order of the item. The structure looks like this: Array ( [item_order] => Array ( [0] => 0 ...

Looking for someone who has successfully upgraded React Native code from version 0.59 to the most recent version

Is there a way to make my React Native project compatible with the latest version? I am facing a challenge in updating an old React Native project running on version 0.59.10 to the most recent version. Despite trying various methods, I have been unable to ...

When using Jest + Enzyme to test a stateful class component, encountering problems with Material-UI's withStyles functionality is a common issue

I have a React + TypeScript application with server-side rendering (SSR). I am using Material-UI and following the SSR instructions provided here. Most of my components are stateful, and I test them using Jest + Enzyme. Below is an example of one such com ...

TypeScript - Minimize redundancy when defining types for a class and its constructor arguments

Here is a class structure I am currently using: class Person { id?: string = uuid(); name: string; constructor(data: Person) { _.merge(this, data); } } The 'uuid' function generates an id and '_' refers to loda ...

choose a specific element from an array in PostgreSQL

Within my database, there is a column named "CIElabOne". This column is of the type numeric [] ("CIElabOne" numeric[]), consisting of values such as: {9.766934377517181,0.0011685082518947398,-0.0023119569625251746} Unfortunately, I am unable to access the ...

What is the best way to display the integer score on my second activity screen?

I have developed a quiz application that consists of multiple-choice questions. The first activity (MainActivity) displays the text question and choices. In the second activity (QuizImage1), an image question is displayed along with choices. Now, I am w ...

transitioning from angular cli version 1.7 to version 12

Looking for a detailed guide on upgrading from version 1.7 to the latest Angular version (12/11)? I currently have an app running on version 1.7 and couldn't find a step-by-step process here: upgrading angular Would it be safe to assume that the upgr ...

Managing two subscriptions based on conditions in Angular

I'm currently working on a component that includes the following code snippet: this.service().subscribe((result) => { this.service2(result).subscribe((result2) => //other code }} As I strive to follow best practices in Angular development, I&ap ...

Modify the title and go back dynamically in the document

I am currently working on a timer app where I want to dynamically change the document title. The app features a countdown timer, and during the countdown, I was able to display the timer in the document title successfully. However, once the countdown is co ...

Attempting to grasp the concept of Typescript generics

I have a function defined as follows: interface ExtraModels extends Model { unknown: string } const write = async (data: ExtraModels[]) => { console.log(data[0].unknown) } This function is currently working. However, I want to modify it to: cons ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

Error: unable to access cordova in Ionic 2Another wording for this error message could be:

While running my Ionic app using the command ionic serve -l, I encountered the following error message: Runtime Error Uncaught (in promise): cordova_not_available Stack Error: Uncaught (in promise): cordova_not_available at v (http://localhost:8100/bu ...