[英]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.