[英]javascript: object destructuring
我有一个 object:
{
"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
}
我想 object 破坏这个:
{
"role": "WORKER_ROLE",
"uuid": "f0ca9c33-a5b7-48c1-9956-1d4d372475ec"
}
如何让数据object解构出来呢? 我尝试这样做:
const { role, user.uuid } = userAuth;
解构不会构建 object。 您首先需要解构为局部变量:
const { role, user: { uuid } } = userAuth;
然后从它们构建结果:
const result = { role, uuid };
或者,使用没有任何解构的单个语句:
const result = { role: userAuth.role, uuid: userAuth.user.uuid };
您可以有一个 IIFE 来解构 object 并返回解构后的属性:
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);
这是示例答案。 我认为,您应该调用 object 的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.