javascript:对象解构

时间:2019-10-13 19:57:59

标签: javascript ecmascript-6

我有一个对象:

{
  "userAuth": {
    "id": 1,
    "uuid": "e30fa23a-bfe4-495e-b6ac-79d49cb9a5a5",
    "login": 12,
    "password": "",
    "role": "WORKER_ROLE",
    "user": {
      "id": 2,
      "uuid": "f0ca9c33-a5b7-48c1-9956-1d4d372475ec",
      "firstName": "Adrian",
      "lastName": "Pietrzak",
      "email": "test111@test.com",
      "phone": null,
      "avatar": null,
      "street": "string",
      "city": "string",
      "state": "string",
      "zip": "string",
      "createdAt": "2019-10-12",
      "lastLogin": "2019-11-29T20:03:17.000Z",
      "lastLogout": null
    }
  },
  "iat": 1570996289
}

我想反对破坏这一点:

{
    "role": "WORKER_ROLE",
    "uuid": "f0ca9c33-a5b7-48c1-9956-1d4d372475ec"
}

如何使数据对象解构出来?我尝试这样做:

const { role, user.uuid } = userAuth; 

3 个答案:

答案 0 :(得分:4)

解构不会构建对象。您首先需要将其分解为局部变量:

const { role, user: { uuid } } = userAuth;

然后从中构建结果:

const result = { role, uuid };

或者,使用单个语句而不进行任何破坏:

const result = { role: userAuth.role, uuid: userAuth.user.uuid };

答案 1 :(得分:0)

您可以拥有一个IIFE来对对象进行解构并返回解构后的属性:

const data = {
  "userAuth": {
    "id": 1,
    "uuid": "e30fa23a-bfe4-495e-b6ac-79d49cb9a5a5",
    "login": 12,
    "password": "",
    "role": "WORKER_ROLE",
    "user": {
      "id": 2,
      "uuid": "f0ca9c33-a5b7-48c1-9956-1d4d372475ec",
      "firstName": "Adrian",
      "lastName": "Pietrzak",
      "email": "test111@test.com",
      "phone": null,
      "avatar": null,
      "street": "string",
      "city": "string",
      "state": "string",
      "zip": "string",
      "createdAt": "2019-10-12",
      "lastLogin": "2019-11-29T20:03:17.000Z",
      "lastLogout": null
    }
  },
  "iat": 1570996289
}


const result = (({ role, user: { uuid } }) => ({role, uuid}))(data.userAuth);

console.log(result);

答案 2 :(得分:0)

这是示例答案。我认为,应该调用对象的userAuth属性。

const obj = {
      "userAuth": {
        "id": 1,
        "uuid": "e30fa23a-bfe4-495e-b6ac-79d49cb9a5a5",
        "login": 12,
        "password": "",
        "role": "WORKER_ROLE",
        "user": {
          "id": 2,
          "uuid": "f0ca9c33-a5b7-48c1-9956-1d4d372475ec",
          "firstName": "Adrian",
          "lastName": "Pietrzak",
          "email": "test111@test.com",
          "phone": null,
          "avatar": null,
          "street": "string",
          "city": "string",
          "state": "string",
          "zip": "string",
          "createdAt": "2019-10-12",
          "lastLogin": "2019-11-29T20:03:17.000Z",
          "lastLogout": null
        }
      },
      "iat": 1570996289
    }

const {role, user: {uuid} } = obj.userAuth;

console.log({role: role, uuid: uuid}) // this gives output, that you expect