Deep copying arrays in Typescript using the spread operator

I'm really struggling to grasp the concept of the spread operator in TypeScript.

Every time I try to use it to duplicate object1.

  let object2 = { ...object1, };

I end up with a brand new object2 that contains all the items from object1, even if there are nested objects involved.

But when object1 includes an array, the spread operator seems to only make a shallow copy. This means that the relationship between the array values in object1 and object2 is maintained.

Is there any method to achieve a deep copy of arrays using the spread operator?

Answer №2

When requiring a deep copy, you could consider the following approach:

var newObj = JSON.parse(JSON.stringify(originalObj));

Answer №3

The spread operator simply duplicates the references to the elements in the initial array, maintaining pointers to the same memory locations.

To achieve a deep copy, I utilize the cloneDeep method from lodash.

Answer №4

While this response may not directly address the question at hand, I would like to share my approach. In my TypeScript projects, I typically utilize classes for object definitions and constructors for deep copying objects of the same type. This allows for passing objects of the same type or their attributes directly using two different constructors.

export class MyObject {
  myAttribute: string;
  otherAttributes: Array<string>;

  constructor();
  constructor(myAttributeOrObj?: MyObject | string);
  constructor(myAttributeOrObj?: any, otherAttributes: Array<string>) {
    if (myAttributeOrObj && myAttributeOrObj.myAttribute) {
      this.myAttribute = myAttributeOrObj.myAttribute;
      this.createOtherAttributes(myAttributeOrObj.otherAttributes);
    } else {
      this.myAttribute = myAttributeOrObj;
      this.createOtherAttributes(otherAttributes);
    }
  }

  createOtherAttributes(arr) {
    this.otherAttributes = [];
    for (var i = 0; i < arr.length; i++) {
      this.otherAttributes.push(arr[i]);
    }
  }

}

Although this method might introduce some overhead compared to utilizing existing libraries, it gives you complete control over your objects, types, and ensures a deep copy instead of a shallow one.

For more insights on constructor overload in TypeScript, refer to this informative discussion Constructor overload in TypeScript.

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

Encountered a RunTime Error when attempting to Lazy Load a module

When attempting to lazy-load a component separately, an unexpected run-time error is occurring. This issue is specifically related to writing loadChildren within the routing module of another component in Angular 6. Any assistance with resolving this error ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

AfterViewInit is not being impacted by property binding in the view

I'm currently integrating Mapbox into my Angular project and I am facing a challenge in displaying information from my component.ts file in the corresponding component.html. My approach involves using mat-vertical-stepper, where each step represents ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

When an unexpected error occurs, the Angular code will terminate the loop

My code currently stops running when the server quits due to an unhandled exception. I want to make two additions to the code, but I'm unsure where to place them. I need to add error handling for exceptions, capturing the error and displaying it. ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

Dealing with Errors in Angular 2/4 using forkJoin for Multiple URLs

I am currently using Angular 2 and implementing forkJoin for a particular scenario where I need to make multiple REST calls in parallel. Below is the function I am using: private getBatchObservableData(data: Array<Widget>): Observable<any> { ...

I am encountering syntax errors with the @Page decorator and constructor () while working on the Ionic 2 template project

Recently, I created an Ionic 2 beta app, but encountered syntax errors when opening it in Visual Studio (VS) 2015. The errors were present inside all the .js files for the @Page decorator and the contructor () { }. As a newcomer to Ionic 2, pinpointing whe ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

Errors in TypeScript are being brought up by using if-else statements inside a loop

I am currently working on a function to retrieve referral codes from users. The user inputs a code, which is then checked against the database to see if it exists or not If the code provided matches the current user's code, it should not be accept ...

Developing components and injecting them dynamically in Angular 2 using Typescript remotely

I am currently exploring the potential of Angular 2 as a foundational technology for a flexible administration dashboard, emphasizing the need for extensibility and customization. I envision an environment where external developers can create their own c ...

Sorting arrays in Typescript

Is there a way to alphabetically sort an array of objects in Typescript based on a specific field? The array I have currently looks like this - https://i.stack.imgur.com/fQ3PA.png I'm interested in sorting it alphabetically by the 'channel' ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

Can you tell me what that sequence of characters is at the conclusion of a styled-component?

Technology Stack: React, Typescript I believe this question may have been asked before, but I am unsure how to search for it... I am interested in creating a wrapper for the styled-components library... Here is the API reference for the specific packag ...

Implementing dynamic Angular form group array with conditional visibility toggling

Within my angular application, I am faced with the task of implementing a complex form. Users should be able to dynamically add, remove, and modify elements within the form. Each element consists of a group of inputs, where some are conditionally hidden o ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...

Calling an HTTP client request with consideration for variable scope

When operating within a well-functioning cloud environment, I encounter an interesting dilemma. While inside the request1 call, I am successfully able to retrieve the output for bodydayOfTheWeek variable. However, upon venturing outside the request1 call, ...

Displaying error messages from custom validators in Angular 6 reactive forms using their own data

In my application, I am working with a FormArray within a FormGroup. Each FormArray consists of multiple FormGroup instances that can be added dynamically. One of the features in my application is a Custom Validator that checks for repeated data across al ...