Cloning objects in Angular v2 and above using TypeScript with getters

Is there a way to efficiently duplicate a TypeScript class without losing getters and ensuring that nested classes and array items have new references?

I have attempted using JSON.parse(JSON.stringify(obj));, but this method does not copy the getters. On the other hand, Object.assign(target, source); successfully copies the getters, but the array items retain their original references.

Below is the structure of the classes:

export interface IClassA {
  code: number;
  description: string;
}

export class ClassA implements IClassA {
  code: number;
  description: string;
  get descrAndCode() {
    return 'Getter A ' + this.description + ':' + this.code;
  }
}

export interface IClassB {
  name: string;
  code: number;
  classList: Array<ClassA>;
}

export class ClassB implements IClassB {
  name: string;
  code: number;
  get codeAndName(): string {
    return 'Getter B' + this.code + ':' + this.name;
  }
  nested: ClassA;
  classList: Array<ClassA>;  
}

Answer №1

To create a deep copy of an object while utilizing both getter and setter methods, you can employ the lodash clonedeep() function as shown below:

import * as cloneDeep from 'lodash/cloneDeep';
...
let copiedObject = cloneDeep(originalObject);

I trust this explanation proves useful to you!

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

What is the process for performing interpolation in Angular version 8?

In my Angular project, I have 2 components working together. Component A sends an id using the following code snippet: <a [routerLink]="['/numbersbyareacode', element.id]"> {{element.title}} </a> Upon navigating to Component B, ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...

The issue with importing fonts in CSS causing an error is encountered when utilizing an exported Angular library

I have a components library for Angular that relies on line-awesome icons. To include the necessary fonts and styles, I am using a CDN in the main SCSS file as shown below: @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400; ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

An error is being thrown in the Angular build due to an issue with parsing JSON after stripping out

Currently, I am working with angular nx alongside nestjs. Upon cloning the project and executing the yarn command, it successfully builds. However, whenever I try to install any package and compile the project, an error is thrown: **D:\projectNAme&bso ...

Utilizing Props in TypeScript with React Styled Components

I created this styled component using TypeScript following the guidelines in their documentation import matrix from '../img/matrix.jpg'; const Style = styled.div` .fixed { background-image: url(${props => props.image ? pr ...

Submitting forms using Ajax in Angular 2

As a novice in Angular 2, with some experience in AngularJS, I am looking for guidance on how to utilize $.ajaxSubmit() or a similar method to submit a form using AJAX instead of the default form submission. Specifically, I am interested in uploading files ...

Enhance the functionality of 'takeWhile' by incorporating a limit parameter, similar to how 'take' operates

I am attempting to retrieve all pages until either there are no more pages or a certain limit (let's say 10 pages) is reached. If I follow this approach: obs.pipe(expand((page) => { return service.call(page).nextPage; }), take(10), takeWhil ...

Searching with Mat-autocomplete across multiple fields simultaneously

I am struggling with a mat-autocomplete that contains 5000 objects, each consisting of a first name and a last name. My goal is to search for both the first name and last name simultaneously regardless of the input order. Currently, I can only search one ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. https://i.sstatic.net/ogFA3.png The content provided was considered valid. https://i.sstatic.net/ar5FJ.png An error ...

Error: ionic serve is unable to locate the 'reflect-metadata' module

I am new to Ionic2 and following the steps: $ npm install -g ionic cordova $ ionic start cutePuppyPics --v2 $ cd cutePuppyPics $ ionic serve However, I encountered an error: "Cannot find module 'reflect-metadata' $ ionic info Cordova CLI: 6.5 ...

A guide on creating a karma-Jasmine test for a dynamic JSON configuration file

Exploring the realm of writing tests with Karma and Jasmine is a new venture for me. In this scenario, I am faced with a dynamic configuration file that is loaded before the initialization of the app. The configuration file is in JSON format and holds a sp ...

Issue with index creation using the @index decorator in Typegoose with NestJS and MongoDB

Encountering an issue with typegoose. Trying to create a 2dsphere index on the property geoLocation of model SP. Utilized the typegoose decorator @index but it's not functioning and not throwing any errors. Uncertain about how typegoose handles this s ...

Encountering a Typescript error while attempting to extract state from a History object containing an enum property

My enum structure is as follows: enum values { first, second, } Within my component, I handle the history object like this: const { push, location: { state = {} } } = useHistory(); Additionally, in the same component within a useEffect hook, I have ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

Azure pipeline failing to run Visual Studio 2017 task because of outdated Typescript SDK version

The Visual Studio 2017 build encounters an error during the build process src\Service\node_modules\utility-types\dist\aliases-and-guards.d.ts(10,51): Error TS2304: Build:Cannot find name 'bigint This issue is specific to the ...

Connect ngModel value between multiple components

If you have a file named about.component.ts, it would contain the following code: import { Component } from '@angular/core'; @Component({ selector: 'about-section', template: ` <input [(ngModel)]="name" placeholder="First N ...

Is it possible to verify type property names using a union type?

Given type UnionType = 'prop1' | 'prop2' | 'prop3'; type DerivedType = { prop1: string; prop2: number; prop3: boolean; }; Is there a method to define DerivedType in such a way that if I introduce a new member to UnionT ...

Automatic Slider for Ionic 4

I am having trouble getting the ionic slider to slide automatically, even though it contains images and the data is fetched from an API call. <ion-slides autoplay="5000" loop="true" speed="300" pager="true" > <ion-slide *`ngFor`="let ...