Transforming a Typescript class instance into a JavaScript object

Here is the code snippet I am working with:

class A{
    test: string
    constructor(test: string){
        this.test = test
    }
}
const a = new A("hi")
console.log(a)

This is what the output looks like:

A { test: 'hi' }

However, when attempting to upload this as a JavaScript object, it gets rejected since it's not recognized as one. One way to work around this is by using JSON.stringify and JSON.parse methods as shown below:

const someJSON = JSON.stringify(a)
const javascriptObject = JSON.parse(someJSON)

Although this method works, I believe there might be a more efficient solution that does not feel like a workaround. Is there a better way to convert a TypeScript class instance into a plain JavaScript object?

Answer №1

If you prefer a simple JavaScript object over a class instance, you can use the spread operator to copy the properties like this:

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }
}

const myCar = new Car("Toyota", "Corolla");
const carCopy = { ...myCar };

console.log('Original car:', myCar);
console.log('Copied car:', carCopy);
console.log('Is carCopy an instance of Car:', carCopy instanceof Car);

Answer №2

If you want to explicitly set the prototype of your symbol to the default prototype of objects, you can utilize the Object.setPrototypeOf() method like this:

class A {
    constructor(example) {
        this.example = example;
    }
}

const instanceA = new A("hello");
Object.setPrototypeOf(instanceA, Object.prototype);
console.log({ instanceA, proto: Object.getPrototypeOf(instanceA) });

After running this code, instanceA will be equal to { example: "hello" }.

Answer №3

In preparation for the future, it is advisable to consider adding additional methods to your class. It is possible that certain properties may need to be made private at some point. To facilitate this transition, a method called toObject can be implemented. This method will allow you to interact with data in the required format efficiently.

class B{
      constructor(private _info: string){

      }

      public toObject(){
        //return JSON.parse(JSON.stringify(this));
        //if underscored private variables are desired
        let obj = {};
        Object.keys(this).map((key: string) => {
          obj[key.slice(1)] = this[key];
        });

        return obj;
      }
    }

    const b = new B("hello")
    console.log(b);
    console.log('----------------------');
    console.log(b.toObject());

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

update/renew angularjs unique directive

Incorporating the carousel plugin from Ionic Market into my ionic project has been a game changer. This specific plugin, known as Morph Carousel, is a custom AngularJS directive that allows me to display content in a visually appealing way. One unique as ...

Transforming Text Using Random Characters Without Altering its Layout

What is a simple method to replace characters in a string while keeping the original format intact? For instance, if a string contains a phone number like 111-222-3333. My goal is to replace this number with a randomly generated one while maintaining the ...

Tabulator now maintains the position of the rightmost column when adjusting the width of table columns

Is there a way to keep the right most column in a fixed position when adjusting column sizes? Whenever I try to resize a column, the right most column moves along with it, causing a gap or horizontal scroll bar to appear. How can I adjust all the columns ...

Discover the data type of a class attribute's accessor methods in TypeScript

Since TypeScript 4.3 introduced the ability for class properties to have getters and setters of different types since 4.3, I am unsure how to correctly retrieve the types of a property's getter and setter. === Since a class property is treated as a ...

Having trouble accessing previously submitted form values in Angular

When I try to update the form, I notice that my meetupform.controls.day array is not retaining the previously selected values app.component.html <div *ngIf="meetupForm.controls.recurring.value==='weekly'"> <mat-checkbox (change)="o ...

Use an array to store nested JSON fields

I'm currently seeking to enhance my proficiency in utilizing JavasScript, React, and Material-UI. I am faced with the challenge of sorting my table using a nested JSON structure and I am encountering difficulties with assigning the JSON fields to my a ...

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

What steps can I take to avoid random divs from overlapping on smaller screens when dealing with elements created in the created() hook?

I encountered an issue with the code I'm working on (the circles overlap in the fiddle provided, but display correctly on my PC - possibly due to pixel discrepancies in the fiddle). You can find the code here. TestCircle.vue: <template> <d ...

"Running 'npm run build' in Vuejs seems to have a mind of its own, acting

Recently, I completed a project and uploaded it to Github. The issue arises when I attempt to clone it to my live server - only about 1 out of 10 times does everything function correctly after running npm run build. My setup consists of Ubuntu 16 with ngin ...

What are the best practices for integrating Qt with React in TSX?

While I've figured out how to communicate qt with JS successfully, the challenge arises when trying to use React in TSX for frontend development. The previous solution failed on this front. Backend code: #./main.py import os from PySide6.QtWidgets ...

Is it possible for Chrome to permit my extension to send HTTPS requests to a server with a self-signed certificate?

My question is about sending AJAX (HTTPS) requests to a server that I own from the background page of my Chrome extension. I have found that without adjusting browser settings, it is difficult to send such requests to an unsigned/self-signed server. I am c ...

What is the best way to generate an error message in AJAX?

It seems that I am facing an issue with throwing an error message to indicate whether an email exists in my user table. I have realized that due to the asynchronous nature of AJAX, try and catch error messages cannot be used within the complete function. E ...

Click to execute instantly without encountering any errors

I'm working with a modal in React JS and I want to trigger a function when the modal opens. I currently have a button function that is functioning correctly using the following code: <button onClick={functionExample("stringParam", true)} ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

Can you outline the key distinctions between AngularJS and ReactJS?

Looking to create a website that will be converted into a mobile application, I realize that my expertise lies more in desktop and Android native development rather than web client side development. After some research, I have decided to utilize HTML5, CSS ...

Unique custom babel plug-in - JSXElement traversal not supported

I'm currently in the process of creating my very own babel transform plugin. When I examine the AST for a React component using astxplorer.net, I notice that JSXElement appears in the tree as a node. However, when I attempt to log the path for the vi ...

What is the best way to prevent duplicates in a Material-UI dropzone area?

Currently, I am utilizing the Material-UI Dropzone component from https://yuvaleros.github.io/material-ui-dropzone/ and my goal is to prevent users from uploading duplicate files that have been previously uploaded. I attempted using an onchange function t ...

Transmit a JavaScript function using JSON

I am working on a server-side Python script that generates a JSON string with parameters for a JavaScript function on the client side. # Python import simplejson as json def server_script() params = {'formatting_function': 'foobarfun&apo ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

Is there a way to adjust the height of mat-sidenav-content to be 100%?

I'm having trouble scrolling down my mat-sidenav-content to reach the bottom where my pagination is located. When I try using fullscreen on mat-sidenav-container, my mat-toolbar disappears. How can I adjust my mat-sidenav-content based on the content? ...