[英]javascript: object destructuring
I have a this object:我有一个 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
}
and I would like to object destructing to this:我想 object 破坏这个:
{
"role": "WORKER_ROLE",
"uuid": "f0ca9c33-a5b7-48c1-9956-1d4d372475ec"
}
how to make data object destructuring out of it?如何让数据object解构出来呢? I try to this:我尝试这样做:
const { role, user.uuid } = userAuth;
Destructuring doesn't build an object.解构不会构建 object。 You first need to destructure into local variables:您首先需要解构为局部变量:
const { role, user: { uuid } } = userAuth;
then build the result from them:然后从它们构建结果:
const result = { role, uuid };
Alternatively, use a single statement without any destructuring:或者,使用没有任何解构的单个语句:
const result = { role: userAuth.role, uuid: userAuth.user.uuid };
You can have an IIFE that destructures the object and returns the destructured properties:您可以有一个 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);
This is sample answer.这是示例答案。 I think, that you should call userAuth property of your object.我认为,您应该调用 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.