简体   繁体   English

在javascript中反转对象键

[英]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.但这与我的 DTO 课程不一致。 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.我试图在 Typescript 中结合类型和 Partial 方法,但后来我不得不使用any一词 - 我想避免这种情况。

How to write functions in JS, who will turn it back? JS怎么写函数,谁来背?

1- Why not to change your DTO 1- 为什么不改变你的 DTO

2- May be you can ask to the Backend dev to change the data sctructure 2-也许您可以要求后端开发人员更改数据结构

3- You can just create an object restructured , To avoid to create some complex function to manipulate the object keys while keys stay statics. 3-您可以创建一个重构的对象,以避免创建一些复杂的函数来操作对象键,而键保持静态。 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,
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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