简体   繁体   中英

How do I destructure this deep nested object?

I have this function below:

const displayUserPhotoAndName = (data) => {
    if(!data) return;

    // add your code here

    clearNotice();
  };

the data parameter is an API from https://randomuser.me/api/

The assignment has the instructions below:

Locate the displayUserPhotoAndName function and do the follwing within it:

  • After the first if(!data) return; statement that terminates the
    function if the expected data parameter is not provided, create a
    statement that de-structures the data parameter and obtains the
    results property from it;

  • Create a second statement in the next line that de-structures the results variable you just created, and obtain the first item from it (it is an Array! See https://randomuser.me/api/ ). Your de-structured array item should be declared as profile. This represents the profile data for the user gotten from the API call that you want to display in your app.

Step 3 Still within the displayUserPhotoAndName function :

  • Set the HEADING element in your app to display the title, last name, and first name (in that order, separated by a single space) of the user profile returned by the API.
  • Set the IMG in your app to display the large photo of the user profile returned by the API.

what I have done:

const displayUserPhotoAndName = (data) => {
    if(!data) return;

    // add your code here
    const {results} = data.results;
    const [profile] = results;
    const {title, First, Last} = results;
    const [,,,,,,,,,picture] = results;
    const largeImage = picture.large;
    userImage.src = largeImage;
    headerUserInfo.innerText = title + ' ' +  First + ' ' + Last;
    clearNotice();
    displayExtraUserInfo(profile);
  };

The error I get:

You have not de-structured the 'results' property from the 'data' parameter passed to 'displayUserPhotoAndName' function

I'm in dire need of assistance. Thanks in anticipation

I'm not going to provide you the full answer but giving you the hints:

const { results } = data
const { profile } = results
console.log(profile)

Can be written as:

const { results: { profile } } = data
console.log(profile)

Here are my some posts from which you may go further:

destructure an objects properties

how is this type annotation working

why source target when destructuring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM