Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object?

Answer №1

When dealing with class instances, remember that they are objects. This means you can utilize regular object prototype functions on them, like in the example below.

class MyClass {
  _a=0;
  _b=0;
  constructor(a, b){
    this._a=a;
    this._b=b;
  }
  
  set a(a){
    return this._a = a;
  }
  
  get a(){
    return this._a;
  }
  
  set b(b){
    return this._b = b;
  }

  get b(){
    return this._b;
  }
}

const instance = new MyClass(2,3);

console.log("keys", Object.keys(instance))
console.log("values", Object.values(instance))
console.log("entries", Object.entries(instance))

instance.a = 5;
instance.b = 5;

console.log("keys", Object.keys(instance))
console.log("values", Object.values(instance))
console.log("entries", Object.entries(instance))

It's important to note that this will only display the actual parameters and will not include any setters or getters.

Answer №2

I'm having trouble grasping the question at hand. If you're looking to transfer all field values from class 1 to class 2, you can achieve this using:

Object.assign(cl2, cl1);

For a complete demonstration (you can test it here, just click on "Run"):

class Class1 {
    public a: number = 1;
    public b: number = 2;
    public c: number = 3;
};

class Class2 {
    public a?: number;
    public b?: number;
    public c?: number;
};

let cl1 = new Class1;
console.log('1 = ', cl1, cl1 instanceof Class1, cl1 instanceof Class2)

let cl2: Class2 = new Class2;
Object.assign(cl2, cl1);

console.log('2 = ', cl2, cl2 instanceof Class1, cl2 instanceof Class2);

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

The value of form.formGroup is not equivalent to the output of console.log(form)

Having an issue here. When I send a Form to a component, If I use console.log(form), it displays the object correctly. However, when I check the form in the console, the form.formGroup.value looks fine (e.g. {MOBILE0: 'xxx', PHONE0: 'xxx&ap ...

Using Angular to access HTML content through the .ts file

Is there a way to retrieve the value of the input field [newUser] when clicking on the button and executing the action [onAddUser()] in the .ts file? <input type="text" ng-model="newUser" style="text-align:center"/> <button (cl ...

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...

Can someone assist me in understanding the proper syntax for the Node.js function that inserts a document into Watson's Discovery service from the watson-developer-cloud library?

I'm attempting to upload JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK. Here is the relevant code snippet: const DiscoveryV1 = require('watson-developer-cloud/discovery/v1'); const discovery = new D ...

Guide on navigating to a different page using a function with router link in Angular using TypeScript

Trying my hand at Angualar and Typescript for the first time. I am working on creating a login page where users can move to another page if their credentials are correct. To achieve this, I want to use a function that is triggered by clicking a button. How ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

When refreshing a page in Next.js, the loading indicator does not properly turn off

I'm currently working on my portfolio using next.js and I have implemented a 'loading' state to prevent displaying partially loaded gallery images. The 'loading' state should turn off (set to 0) once all the photos are fully loaded ...

Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks. My failed attempts so far: $('.chips').on('chip.delete', function(e, chip){ console.lo ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

Issue with File Input not being validated by Bootstrap Validator

Looking for help with a form field that should only accept .jpg or .png images of a certain file size. The validation doesn't seem to be working when tested with invalid file types. What am I missing? It should function like the example shown here. C ...

What is the best way to incorporate AJAX with Node.js?

After testing the Hello world program with Node.js, I can confirm that it is working perfectly. Here are the file details: index.html socket.js To run in command prompt: node socket.js I also experimented with ajax calls in Node.js using the same hel ...

What is the best way to detect component errors on the server with Angular Universal?

Here is a snippet of my server code that renders the Angular home.component: app.get("*", (req, res) => { res.render( `../${CLIENT_DIST_DIR}/index`, { req: req, res: res, providers: [ ...

Tips for minimizing unnecessary rerenders in child components that rely on cached information from the parent component

check out the sandbox here Application maintains state to compute a memoized value, which is then passed as props to the Options. When a change occurs in the state triggered by a callback function in Option, it causes a rerender of the main Application, r ...

When sending an AJAX request to a URL, can I verify in the PHP page whether it is a request or if the page has been accessed?

In order to enhance security measures, I need to prevent users from accessing or interacting with the php pages that will be utilized for ajax functionality. Is there a method available to determine if a page has been accessed through an ajax request or b ...

The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keepin ...

Encountering difficulty in reaching the /login endpoint with TypeScript in Express framework

I'm currently working on a demo project using TypeScript and Express, but I've hit a roadblock that I can't seem to figure out. For this project, I've been following a tutorial series from this blog. However, after completing two parts ...

How can I force an element to overflow without being affected by its parent's overflow style in CSS/HTML/JS, even if the parent is

I've come across many inquiries on this subject, but the proposed solutions never seem to work when dealing with ancestors that have absolute positioning. Take this example: <div id='page'> <div id='container' style= ...

Is it feasible to obtain multiple tag-name indexes using JavaScript?

Exploring the table search function provided by W3Schools has brought up an interesting question in my mind. Is it feasible to simultaneously retrieve multiple indexes using getElementsByTagName and conduct a search across the entire table instead of just ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Enhancing Performance by Optimizing Module Loading for Frontend Component Rendering in Next.js

When building a Nextjs app, it is common to use the same package across multiple components on a page. However, in the case of client-side rendering, the default behavior does not optimize the loading of the common package. This can result in a significant ...