[Fixed] Rename variable name received from server?

Issue

I am getting data from service in the following format

Backend- first_name
Frontend- firstName 

yourData.ts file

export interface YourData {
    first_name: number;
}

On the UI Angular I would like to display the format to Lower camel case

html

firstName is {{firstName}}

How can I solve?

Solution

You cannot rename fields of an object when it is present. You have 2 options here.

1st

Define 3 optional fields in your interface

export interface YourData{
   first_name: number;
   firstName?: number;
}

And then you put a method in between where you just map the values.

convertToCamelCase(data: YourData): void {
    data.firstName= data.first_name;
}

The object gets processed "by reference" so you don’t need to return it.

2nd

You build up a second interface with the names in CamelCase and then you do the mapping.

export interface CopyDataInterface{
      firstName: number;
}


convertToCamelCase(data: YourData): CopyDataInterface{
   // instantiate an object dupdata using the interface CopyDataInterface
   // [...]
    dupdata .firstName= data.first_name;
    return dupdata;
}

Leave a Reply

(*) Required, Your email will not be published