Tejas Mehta
Tejas Mehta

Reputation: 301

Typescript/ Angular - How can I rename object received from server?

I am getting data from service in the following format

yourData.ts file

export interface YourData {
    first_name: number;
    last_name: number;

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

html file

firstName is {{firstName}}
lastName is {{lastName}}

Where and how can I make the above change?

I was planning of something like, not sure if thats right

export const parseFromServer = (response:any) =>{
    return {
        firstName : response.first_name
    }
}

Upvotes: 1

Views: 913

Answers (2)

Deepak
Deepak

Reputation: 2742

UPDATED:

If you wish to make use of the same object, the approach is to add a new key and delete the old key. Please check the old answer if you wish to make use of a new object.

    var oldObject: any = {
        first_name: 1,
        last_name: 2
    }
    var keys = Object.keys(oldObject);
    for(var key in oldObject) 
    {
        let words = key.split("_");
        oldObject[words[0][0].toLowerCase() + words[0].substring(1) + words[1][0].toUpperCase() + words[1].substring(1)] = oldObject[key]; // add new key
        delete oldObject[key]; // delete old key
    }
    console.log(oldObject)

All you need to do is just make sure there the key names are unique and the word format is {word1}_{word2}

OLD ANSWER:

From the comment, I understand you wish to rename your object keys from something like first_name to firstName. You cannot rename as such, but you can create a new object with the desired key names and assign the appropriate values.

From your example, if you know the key names already, then it is straightforward:

var oldObject = {
    first_name: 1,
    last_name: 2
}
var newObject = {
  firstName: oldObject.first_name,
  lastName: oldObject.last_name
}; 
console.log(newObject)

If you don't know the key names, but you know the format is {word1}_{word2}, then you can write your own logic. Here's one:

var oldObject: any = {
    first_name: 1,
    last_name: 2
}
var newObject: any = {};
var keys = Object.keys(oldObject);
for(var key in oldObject) 
{
  let words = key.split("_");
  newObject[words[0][0].toLowerCase() + words[0].substring(1) + words[1][0].toUpperCase() + words[1].substring(1)] = oldObject[key];
}
console.log(newObject)

Here's the playground.

Upvotes: 1

A Indu
A Indu

Reputation: 25

I think you can try this approach, not sure if it will work in your case - https://levelup.gitconnected.com/spreading-resting-and-renaming-properties-in-typescript-68fb35ffb1f

Upvotes: 0

Related Questions