Transform the data received from the server into a TypeScript object

I'm facing a challenge in converting an object retrieved from the server to a TypeScript class I've created.

While my TypeScript object has identical properties to the one returned by the server, the difference lies in the casing of the property names. The properties in my TypeScript class are camel cased, whereas those in the server's object are title cased. This mismatch causes issues when trying to access properties like userModel.isActive in my TypeScript code. Below is the API call return statement made by my provider.

return this.httpClient.post<UserModel>(url, { params: queryParams });

I have attempted:

this.userProvider.getUser(request).subscribe(modelReturnedFromApi => {
    Object.assign(this.myTypeScriptModel, modelReturnedFromApi)
    this.myTypeScriptModel = modelReturnedFromApi
    this.myTypeScriptModel = JSON.stringify(modelReturnedFromApi)
})

Could someone provide guidance on how to resolve this issue? Thank you in advance.

Update: It seems that there isn't a built-in solution for what I require, so I've decided to align the property names in my TypeScript class with those returned from the server. Appreciate all the support provided.

Answer №1

When the names of your properties are not identical, you might need to manually assign each property of myTypeScriptModel to the corresponding property in modeReturnedFromApi.

Answer №2

A method to convert title-cased properties to camel-cased properties would involve iterating through each property of the model returned from the API and assigning the value to a new property with the first letter in lowercase.

for (let property in apiModel) {
    myTypeScriptModel[property[0].toLowerCase() + property.substr(1)] = modelReturnedFromApi[property];
}

This approach is only suitable for handling properties at one level. For nested objects with title-case properties, a recursive function will be required. If you face difficulties implementing this solution, please provide an example input and I can modify the answer accordingly.

Answer №3

If you're expecting a specific response, consider creating a model class and using its constructor function to convert the data into camelCase format.

Person.ts

export class Person {
  firstName: string;
  lastName: string;

  constructor(person){
    this.firstName = person.Firstname;
    this.lastName = person.Lastname;
  }
}

app.component.ts

export class AppComponent implements OnInit {
  name = 'Angular';
  person: Person;

  // sample response for demonstration purposes
  response = {
    'Firstname' : 'John',
    'Lastname': 'Doe'
  }

  ngOnInit(){
    // converting response into a Person object
    this.person = new Person(this.response);
  }
}

You can check out this stackblitz for more details.

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 could be causing the errors I'm encountering in my TypeScript component within AngularJS?

I am working with an AngularJS component written in TypeScript called news.component.ts. This component makes a call to a service named google.service.ts in order to fetch news RSS using a service that converts XML to JSON. Within the NewsComponent, I hav ...

Utilizing React with .NET 8.0 and Minimal API, the front end is configured to send HTTP requests to its own specific port rather than the

Transitioning from working with react projects on .NET 3.1 to creating a new project on .NET 8.0 has been a challenging and confusing experience for me. When I attempted to access a newly created controller method, I encountered the error 404 Not Found. It ...

Problems encountered with operating the Bootstrap burger menu

After following the Bootstrap navbar documentation and implementing the code in my bs-navbar.component.html file, I encountered an issue with the hamburger menu. Despite everything being set up correctly, clicking on the hamburger icon did not display the ...

Enhancing the aesthetic appeal of Angular2 Google Maps

Hey there, I'm a newcomer to Angular2/Typescript and I've been working on styling a map in my Angular2 project. I integrated a map using the Angular2 Google Maps Components, but I'm having trouble with applying styles through the undocumente ...

Creating a build task in Visual Studio Code with universal TypeScript compiler settings

Our project has the following structure: +-- views +-- viewXXX +-- ts ¦ +-- controller.ts ¦ +-- helper.ts ¦ +-- ... (*.ts) +-- viewXXX.ctrl.js // this is the desired output file +-- viewXXX.c ...

Locate the minimum and maximum values between two inputted dates

I'm looking for a solution that provides strongly typed code. The problem arises when trying to implement solutions from a related question - Min/Max of dates in an array? - as it results in an error. TS2345: Argument of type 'Date' is not ...

The color scheme in Visual Studio 2019 for Angular and Typescript code is quite unappealing

https://i.sstatic.net/DFdhm.png Currently following a Udemy course on Angular (Using Angular, Angular Material, Angularfire (+ Firebase with Firestore), and NgRx to create a functional Angular App). Instead of using VS Code, I decided to use Visual Studio ...

forEach was unable to determine the appropriate data types

define function a(param: number): number; define function b(param: string): string; define function c(param: boolean): boolean; type GeneralHooks<H extends (...args: any[]) => any> = [H, Parameters<H>] const obj = { a: [a, [1]] as Gene ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

Unable to transmit props while employing Typescript in ReactJS

Attempting to pass props from components like AllProducts, MenProducts, etc. to the AddToCartButton component for reusability presents a challenge. When trying to pass props using: <AddToCartButton id={product.id} /> An error is encountered: Type & ...

When RxJS returns an empty observable, it does not trigger the successful action

I am working with a Rxjs effect that has the following structure: callApiPostSyncPushEffect$ = createEffect(() => { return this.actions$ .pipe( ofType(SyncActions.callApiPostSyncPushPullAction), mergeMap((action) ...

Adding local images to Excel can be easily accomplished using Office Scripts

Hello, I've been attempting to replace Excel cells that contain image filepaths with the actual images themselves. I found an example in Office Scripts that shows how to insert images with online URLs but doesn't mention anything about inserting ...

Obtain characteristics of the primary element in Ionic version 2 or 3

After creating and opening my Sqlite database and saving the SQLiteObject in a variable within my app.component.ts, I now need to retrieve these attributes in my custom ORM. The ORM extends to other providers to describe the title and field of my tables. ...

The distribution of intersection types is not properly handled by Typescript's array.map function

My array is of type object[] & Tree[], but when using arr.map(child => ...), the type of child is inferred as object instead of object & Tree. Is there a way to avoid this without additional casting? It's worth noting that Tree extends ob ...

Angular Pipe: Working with Data Structures in Angular With Nested Arrays and Objects

After struggling to customize answers for similar questions, I find myself in need of some assistance. My current challenge involves using an angular pipe to filter the following data structure: subjects = [ { name: "subject1", keywords:[& ...

Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function? <div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div> The doubleClick function will ret ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

Customizing pressed row styles and properties within a map iteration in React Native

How can I modify the style of a single item in a list when a button is pressed in React-Native? I want only the pressed item to change, not the entire row. Here is my attempt at implementing this: //hooks const [activeStyle, setActiveStyle] = useState( ...

Is it possible to exclude a certain prop from a styled component that has emotions?

Within my code, there exists a component called BoxWithAs, which is defined as follows: const BoxWithAs = styled.div( { WebkitFontSmoothing: 'antialiased', MozOsxFontSmoothing: 'grayscale' // And more … } ); Everythin ...