简体   繁体   中英

Revesse object keys in javascript

My response after registration looks as follows:

{
    "emailAddress": "test@test.com",
    "id": 43,
    "uuid": "afb9fd83-b989-40c6-bb81-210e053fe19a",
    "createdAt": "2021-07-29T03:13:29.427Z",
    "updatedAt": "2021-07-29T03:13:29.427Z"
    "user": {
        "id": 43,
        "uuid": "588cef19-bbaa-4a91-905e-088d9098a1aa",
        "firstName": "dadadada2",
        "createdAt": "2021-07-29T03:13:29.427Z",
        "updatedAt": "2021-07-29T03:13:29.427Z",
    },
}

But that does not agree with my DTO class. I would like to get a result:

{
    "firstName": "dadadada2",
    "id": 43,
    "uuid": "588cef19-bbaa-4a91-905e-088d9098a1aa",
    "createdAt": "2021-07-29T03:13:29.427Z",
    "updatedAt": "2021-07-29T03:13:29.427Z",
    "authentication": {
        "emailAddress": "test@test.com",
        "id": 43,
        "uuid": "afb9fd83-b989-40c6-bb81-210e053fe19a",
        "createdAt": "2021-07-29T03:13:29.427Z",
        "updatedAt": "2021-07-29T03:13:29.427Z"
    }
}

I tried to combine with types and the Partial method in Typescript, but then I would have to use the word any - and I want to avoid this.

How to write functions in JS, who will turn it back?

1- Why not to change your DTO

2- May be you can ask to the Backend dev to change the data sctructure

3- You can just create an object restructured , To avoid to create some complex function to manipulate the object keys while keys stay statics. like :

    const compatWithDTO = {
    "firstName": res.user.firstName,
    "id": res.id,
    "uuid": res.uuid,
    "createdAt": res.createdAt,
    "updatedAt": res.updatedAt,
    "authentication" {
        "emailAddress": res.emailAddress,
        "id": res.user.id,
        "uuid": res.user.uuid,
        "createdAt": res.user.createdAt,
        "updatedAt": res.user.updatedAt,
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM