Using TypeScript, we can assign a JSON object to an extended class by leveraging the

Task was to include an additional property.

I modified a current class by adding a new property, but when I assign a JSON object from the database, the newly added property disappears. Is there a way to correctly assign a JSON object to a TypeScript class so that the instance retains all properties and prevents data binding errors? I'm trying to avoid writing extra code to manually check the JSON...

Any assistance is appreciated

Example:

let JSONObject = {
 FirstName: "Json",
 LastName: "Born"
};

class Person {
 FirstName: string = "Jason";
 MiddleName: string = "Unknown";
 LastName: string = "Bourne";
}

let PersonA = new Person();

console.log(PersonA); **//{FirstName:"Jason", MiddleName: "Unknown", LastName: "Bourne"}**

PersonA = JSON.parse(JSON.stringify(JSONObject));
//also tried **PersonA = <Person>JSON.parse(JSON.stringify(JSONObject));**


console.log(PersonA); **//{FirstName:"Json", LastName: "Born"}**

Attempted searching for solutions on converting a JSON object to a TypeScript class,

Answer №1

To properly convert the values in your JSON object to a specific object type like a Person, you will need to map them explicitly. This is necessary because the JSON data may not inherently correspond to a predefined object structure.

One approach you could take is outlined below:

let JSONObject = {
 FirstName: "Json",
 LastName: "Born"
};

class Person {
 FirstName: string = "Jason";
 MiddleName: string = "Unknown";
 LastName: string = "Bourne";
}

let PersonA = new Person();
PersonA.FirstName = JSONObject.FirstName;
PersonA.LastName = JSONObject.LastName;
PersonA.MiddleName = "...";

Alternatively...

let PersonA = JSON.parse(JSON.stringify(JSONObject));
PersonA.MiddleName = "...";

It's important to note that if the 'MiddleName' property comes from your web service within the JSONObject assignment, it will be included and can be directly parsed into the class. Otherwise, you will have to handle the mapping yourself as the parsing operation won't automatically know how to process properties like 'MiddleName' that do not exist in the source JSON.

Hope this helps!

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

Alert: TypeScript Linter Warning

When I execute the npm lint command in Circle CI, a warning message is displayed. The following rules specified in the configuration could not be found: templates-use-public no-access-missing-member invoke-injectable template-to-ng-templa ...

The Angular Component I've created is displaying a single set of data on each mat-tab screen

I have developed a component with the file name hukamnama-sahib.component.html, which looks like this: <body *ngFor="let dataitem of HukamnamaSahibList"> <h4> <span class="gurmukhi">{{dataitem.line.gurmukhi.unico ...

How can you toggle the selection of a clicked element on and off?

I am struggling with the selection color of my headings which include Administration, Market, DTA. https://i.stack.imgur.com/luqeP.png The issue is that the selection color stays on Administration, even when a user clicks on another heading like Market. ...

Storing data in Angular 2 services for safekeeping

I have multiple sub-components that each receive specific data from a main component. These sub-components only receive the data necessary for display purposes. My goal now is to create a service that can make a request to a server. The problem is, this re ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

What is the best way to ensure that my mat-slide-toggle only changes when a specific condition is met?

I'm having an issue with a function that toggles a mat-slide-toggle. I need to modify this function to only toggle when the result is false. Currently, it toggles every time, regardless of the result being true or false. I want it to not toggle when t ...

Using Node.js to set a whitelist limit for express.json

In my Node.js backend, I have multiple routes that do not involve file uploads for regular users (with a limit of 50kb). However, I need to create specific routes for administrators to be able to upload files, which would require a higher express.json and ...

Retrieving JSON Data from an API with JavaScript/jQuery

Having some trouble with JSON parsing using jQuery and JavaScript. I'm trying to fetch weather information from the open weather simplest API, but for some reason it's not working. When I hardcode the JSON data into a file or my script, everythin ...

Is there possibly a problem with GridActionsCellItem and its props?

I'm encountering a problem with passing props into the GridActionsCellItem within the '@mui/x-data-grid'; columns; { field: 'actions', type: 'actions', width: 80, getActions: (params: any) =&g ...

Unveiling typescript property guards for the unknown data type

Is there a way to type guard an unknown type in TypeScript? const foo = (obj: unknown) => { if (typeof obj === 'object' && obj) { if ('foo' in obj && typeof obj.foo === 'string') { r ...

Issues with parsing JSON data within PowerShell

While working with JSON, I encountered a specific issue that I need help with. The JSON snippet provided below illustrates the problem: Although I have experimented with various examples of JSON manipulation, most of them focus on simple key/value pairs. ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

Removing the @Input decorator in Angular's codebase

I am currently working on an Angular project for a class, and I'm facing an issue where removing the @Input decorator from my component is causing the entire application to not load properly. import { Component, OnInit, Input } from '@angular/ ...

What is the best way to retrieve specific JSON information?

[["pdf-sample.pdf",["uploads\/28\/pdf-sample.pdf"],{"en":"PDF Sample"},"","28"],["pdf-sample2.pdf",["uploads\/29\/pdf-sample2.pdf"],{"en":"Second PDF sample"},"","29"]] After figuring out how to access the uploads\28\pdf-samp ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

What is the best way to hand off this object to the concatMap mapping function?

I'm currently in the process of developing a custom Angular2 module specifically designed for caching images. Within this module, I am utilizing a provider service that returns Observables of loaded resources - either synchronously if they are already ...

Guide on Implementing Link href in Next.js v12

When I set the href as a string, the link functions properly. However, when I use an object for the href, the link fails to work. Despite seeing the correct querystring when hovering over the link, it always takes me back to the first page. // ProdCard t ...

Storing JSON data retrieved from an API into a class property using the fetch function: a step-by-step guide

I am faced with the challenge of communicating with a localhost API that I have created in my React application class. This API is responsible for returning a list of JSON data, and my goal is to store this data in a property. Having limited knowledge abo ...

Obtaining the value for the last JSON object in onPostExecute()

In my AsyncTask, I have successfully parsed the JSON and retrieved values for both objects, such as image and period. However, in the onPostExecute() method, I am only able to get the value for the last json object. Currently, I am only receiving the valu ...

Tips for retaining the data types of a specific key within a JSON Object when utilizing GSON

I am working with an original JSON String that contains key-value pairs as shown below: { "u":{ "string":"1235" }, "p":"2047935", "client_id":{ "string":"5" }, "origin":null, "item_condition":null, "country_id":{ "int":3 } ...