问题:
I have an object "data" from 'https://randomuser.me/api/' which I'm using in my project.
{
"results": [
{
"gender": "female",
"name": {
"title":...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have an object "data" from 'https://randomuser.me/api/' which I'm using in my project.
{
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
}
I destructured results from the data object as follows; const {results} = data;
How do I destructure the results variable I created, and obtain the first item from it I want the de-structured array item to be declared as profile. This represents the profile data for the user gotten from the API call that I want to display in my app.
回答1:
You can do it like this:
const { results: [firstItem] } = data;
See this MDN article for more info on destructuring.
const data = {
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
};
// declare a const variable named firstItem that holds the first element of the array
const { results: [firstItem] } = data;
// You could event destructure the content of this first array item like this
const { results: [{ gender, name }] } = data;
// or go deeper like this
const { results: [{ name: { title, first, last } }] } = data;
console.log(firstItem);
console.log(gender);
console.log(name);
console.log(title, first, last);
According to your code (see comments), this should work too:
const data = {
"results": [
{
"gender": "female",
"name": {
"title": "miss",
"first": "mia",
"last": "sutton"
}
}
]
};
const displayUserPhotoAndName = (data) => {
if(!data) return;
const { results } = data;
const { results: [profile] } = data;
console.log(profile);
}
displayUserPhotoAndName(data);