1

I have a class

export class User {
constructor(public firstname:string,
public lastname:string
public email:string
public password:string){}
}

I want to send it as a Json but the User data should be a Json object inside another object. The final json should look as follows

{
"external-profile":{
"firstname":"something",
"lastname":"something",
"email":"some@something",
"password":"something"
}

}

How could I do this in Angular? I tried the following two approaches but they don't work

1) creating an object of type User and doing JSON.stringify(user) produces

{
    "firstname":"something", <-- not embedded in external-profile
    "lastname":"something",
    "email":"some@something",
    "password":"something"
    }

2) creating another class UserProfiles as follows

class UserProfile{
constructor(public externalProfile:User){} //I can't use hypen separated variable names in Typescript it seems.
}

the above produces if I create an object of type UserProfile and JSON.stringify it.

{
    "externalProfile":{  <-- I want external-profile, not externalProfile
    "firstname":"something",
    "lastname":"something",
    "email":"some@something",
    "password":"something"
    }

}

1 Answer 1

1

Variable and parameter names can't contain special characters, but class fields can if you quote them, you just can't use the syntactic sugar of constructor parameters to fields:

class UserProfile{
    'external-profile': User
    constructor(externalProfile:User){
        this["external-Profile"] = externalProfile;
    }
}

You don't need another class though you could just call:

JSON.stringify({ 'external-profile': user })
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.