typescript how to duplicate an object without creating reference

I currently have a single object

item = { selectedItems: [] };

Here is what I did:

item1 = { ...item };
item2 = Object.assign({}, item);
item3 = Object.create(item);

However, when I make changes to selectedItems in item1, those changes apply to all items. This is an Angular project. What am I doing wrong? Is there a better approach? Or could it be the browser cache causing this issue? I'm quite puzzled.

Answer №1

If you require a deep copy, consider the following approach:

const duplicateItem = JSON.parse(JSON.stringify(originalItem));

Answer №2

Perhaps the issue lies elsewhere in your code. It seems like the method you are using to clone objects is creating new objects without maintaining references to the original ones. For more detailed information, please refer to the following article: https://dmitripavlutin.com/javascript-shallow-clone-objects/#:~:text=1.-,Cloning%20using%20object%20spread,the%20shallow%20copy%20of%20object%20.

PS: It's possible that there is a logic error in your application where changing selected items does not properly update other variables.

Answer №3

Next time you encounter this issue, consider using the following simple function.

const updatedArray: unknown[] = duplicate(originalArray)

// ...

function duplicate<T>(item: T): T {
  return JSON.parse(JSON.stringify(item));
}

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

Is it possible to encrypt data using a private key in Angular and then decrypt it using a public key in PHP using RSA encryption?

Attempting to Encrypt data using the RSA Public Key in Angular and Decrypt it with the public key in PHP. Encryption is done with the JsEncrypt library in Angular, while decryption takes place in PHP. :openssl_public_decrypt($signature, $decrypted, $public ...

Changing the color of multiple rows in Angular MaterialUI when clicked

I've come across an issue where I'm able to change the color of a cell when I click on showProfile(), but if I click on the next row, the previous color disappears. How can I make sure that the color remains persistent each time I click on any ro ...

Firestore security measures verify modification of document keys

Is there a way to determine which key in a document has been modified in the Firestore security rules? And then verify it against the changed object? I'm struggling with this concept and finding it difficult to test. Appreciate any help! - Ryann ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

Could Angular be automatically applying margins or padding to my component?

I'm encountering a minor issue.. I'm attempting to create a "Matrix" to construct a snake game in angular, but there seems to be an unremovable margin/padding. Below is my code: <!-- snake.component.html --> <div id="ng-snake-main&q ...

Utilize React to display a Selected button within a whitespace

Currently, I am encountering an issue in React where I have a group of buttons at the bottom. Upon selecting a button, the corresponding text should display at the top within a specified whitespace. However, I am looking to have the whitespace already occu ...

Error message: "An issue related to md-input binding has been found in the

I encountered a common error while trying to upgrade an app from angular2 to the stable version. Unfortunately, none of the suggested solutions worked for me, even though there seems to be only one widespread solution available. Here's the error messa ...

A guide on defining global TypeScript interfaces within Next.js

In the process of developing an ecommerce web application with next.js and typescript, I found myself declaring similar interfaces across various pages and components. Is there a method to create global interfaces that can be utilized by all elements wit ...

Trapped in a never-ending cycle caused by failing to dispatch an action within ngrx/effects

My current setup involves using Angular2, ngrx/store, and ngrx/effects for state management. I have encountered an issue where I am unable to display an error message when a specific action fails within an @Effects() block. Here is the problematic code sn ...

Tips for retrieving a reactive variable from a setup() method?

I'm currently working on a small notes app and using Vue3 + Typescript to enhance my skills. The following code snippet demonstrates how to dynamically create and display an Array of notes: <template> <q-layout> <div v-for ...

Discovering Angular: A Guide to Displaying Dropdown Items in Dropdown Buttons

I'm seeking guidance on dropdown buttons. Here is some code I found in an example: <!--adjustbtn is a class I created to style the button--> <button class="dropdown adjustbtn" style="border-radius: 5px; box-shad ...

The CSS formatting is not being properly applied within the innerHTML

I have a scenario where I am trying to display a Bootstrap card using innerHTML in my TS file, but the styles are not being applied to this content. I suspect that the issue might be because the styles are loaded before the component displays the card, cau ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

update or add new data to dataSource to refresh

I am currently working on a project using angular Material and I need to make some modifications to it. Since I am fairly new to Angular, I require assistance in resolving an issue. There is a component in my project that has multiple templates and gener ...

The battle of ng-bullet and karma-parallel: optimizing Angular unit test performance with test module configuration in before all block

I'm currently exploring different options to enhance the speed of my unit tests in an Angular project. After reading several blogs, I came across some suggestions: (1) ng-bullet (2) karma-paralle (3) ng test --browsers ChromeHeadless (4) configu ...

Error: Attempting to access the 'token' property of a null value is not permitted

One of the services I have returns all City data from a web service. @Injectable() export class CityService { constructor(private http: Http, private router: Router, private auth: AuthService) { } public getAllCity(): Observable<City[]> { ...

employing a modal to create an interactive form in Angular

I recently started delving into Angular and I'm aiming to develop a dynamic form that can create entries in my database with fields that vary based on a dropdown selection in the modal header. I've searched for solutions but only found help for c ...

The workspace does not have the 'development' configuration set for Angular 12 Universal

After creating a new Angular 11 project called "client", I updated the Angular version to 12 and installed Universal by running the command: ng add @nguniversal/express-engine. However, when attempting to run my Universal Angular project using the command ...

What could be the reason for passport.serializeUser function not being available?

After spending nearly an hour searching, I am still unable to pinpoint the issue in my code. Not only have I failed to find a solution online, but reaching out for help in coding communities on Discord has also been futile as no one seems to know why this ...

Add the list of information during the looping process (map)

I am currently facing a challenge where I need to update my data during the iteration and send the results to an API call. The API Call expects a request with data structured in the following format: { list: [{ id: "1", name: "Hello" ...