我有一个名为displayUserDetail
的函数,它带有一个api对象,它是从该API — https://randomuser.me/api中作为参数userData
传递的。
这是示例API响应(已整理):
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "peter",
"last": "morris"
},
"location": {
"street": "4330 avondale ave",
"city": "mackay",
"state": "tasmania",
"postcode": 4247,
"coordinates": {
"latitude": "-79.8202",
"longitude": "-177.8268"
},
"timezone": {
"offset": "+7:00",
"description": "Bangkok, Hanoi, Jakarta"
}
},
"email": "peter.morris@example.com",
"login": {
"uuid": "cad308a3-5d94-4269-872b-d0a473c4a269",
"username": "blackpeacock867",
"password": "josephin",
"salt": "x2MrizMY",
"md5": "8a5298049f819b7ffab05853b6480c8c",
"sha1": "7dde7e2aa7e7b3efdbec903fccf7f61d53c6c6dd",
"sha256": "aac87211a73f52df4b54932ee9a4deaabd51c703249f762b8e518f121eeb7b86"
},
"dob": {
"date": "1947-01-10T18:33:20Z",
"age": 72
},
"registered": {
"date": "2012-12-14T12:51:06Z",
"age": 6
},
"phone": "04-2726-1355",
"cell": "0407-597-184",
"id": {
"name": "TFN",
"value": "280671361"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/26.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/26.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/26.jpg"
},
"nat": "AU"
}
],
"info": {
"seed": "26dbd13d59ab09ca",
"results": 1,
"page": 1,
"version": "1.2"
}
}
由此,我需要使用解构从此api获取username
和picture
。
const displayUserDetail = (userData) => {
if (!userData) return;
// ???
}
如何使用销毁方法创建一条语句以从API响应中获取username
和picture
?
答案 0 :(得分:1)
您可以像这样使用解构:
const displayUserDetail = (userData) => {
const {
login: username
} = userData
const {
picture
} = userData
console.log(username)
console.log(picture)
}
let data = {
"results": [{
"gender": "male",
"name": {
"title": "mr",
"first": "peter",
"last": "morris"
},
"location": {
"street": "4330 avondale ave",
"city": "mackay",
"state": "tasmania",
"postcode": 4247,
"coordinates": {
"latitude": "-79.8202",
"longitude": "-177.8268"
},
"timezone": {
"offset": "+7:00",
"description": "Bangkok, Hanoi, Jakarta"
}
},
"email": "peter.morris@example.com",
"login": {
"uuid": "cad308a3-5d94-4269-872b-d0a473c4a269",
"username": "blackpeacock867",
"password": "josephin",
"salt": "x2MrizMY",
"md5": "8a5298049f819b7ffab05853b6480c8c",
"sha1": "7dde7e2aa7e7b3efdbec903fccf7f61d53c6c6dd",
"sha256": "aac87211a73f52df4b54932ee9a4deaabd51c703249f762b8e518f121eeb7b86"
},
"dob": {
"date": "1947-01-10T18:33:20Z",
"age": 72
},
"registered": {
"date": "2012-12-14T12:51:06Z",
"age": 6
},
"phone": "04-2726-1355",
"cell": "0407-597-184",
"id": {
"name": "TFN",
"value": "280671361"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/26.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/26.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/26.jpg"
},
"nat": "AU"
}],
"info": {
"seed": "26dbd13d59ab09ca",
"results": 1,
"page": 1,
"version": "1.2"
}
}
data.results.forEach(userData => displayUserDetail(userData));