简体   繁体   中英

De-structuring of an array object fetched from an API

I have this task of fetching an array object from an API with the url https://randomapi.com/api/d12c99b82acfefae33f7ce9239b57811 , and I need to destructure the array and assign only the results value in that array to a variable data in my code. Here is a sample of what I tried

const displayMenu = ({ results } = {}) => {
            const [data] = results[1];
            menu = Object.values(data);
        };

 const fetchAndDisplayMenu = () => {
     const api = 'https://randomapi.com/api/d12c99b82acfefae33f7ce9239b57811';
          fetch(api)
            .then(response => response.json())
            .then((data) => {
                displayMenu();
                });
        };

It brings an error of the array you are trying to destructure is not iterated?

The object am fetching from the API looks like this

{
  results: [
    {
      "17651135-1987-4d14-af8e-6dd5d5356cab": {
        id: "17651135-1987-4d14-af8e-6dd5d5356cab",
        price: 4829,
        sample: "https://lorempixel.com/640/480/food",
        origin: "Tanzania"
      },
      "bdeb5dc0-3c6c-4b20-9e4a-7d3c9dd9e969": {
        id: "bdeb5dc0-3c6c-4b20-9e4a-7d3c9dd9e969",
        price: 5786,
        sample: "https://lorempixel.com/640/480/food",
        origin: "Congo Brazzaville"
      },
      "12ca14ea-f791-4390-82bf-3b2db8f20311": {
        id: "12ca14ea-f791-4390-82bf-3b2db8f20311",
        price: 3418,
        sample: "https://lorempixel.com/640/480/food",
        origin: "Seychelles"
      },
      "fb2c0876-03b0-4885-9d40-781393903524": {
        id: "fb2c0876-03b0-4885-9d40-781393903524",
        price: 5411,
        sample: "https://lorempixel.com/640/480/food",
        origin: "Eritrea"
      }
    }
  ],
  info: {
    seed: "5e5bcec11b782295",
    results: "1",
    page: "1",
    version: "0.1",
    time: {
      instruct: 10,
      generate: 5
    }
  }
};

You are receiving this error for 2 reasons:

  1. results[1] does not exist
  2. You are not passing any parameters to displayMenu() , so you have no data to work with in the first place.

You should write your code like this:

 const displayMenu = ({ results } = {}) => { const [data] = results; const menu = Object.values(data); console.log(menu) }; const fetchAndDisplayMenu = () => { const api = 'https://randomapi.com/api/d12c99b82acfefae33f7ce9239b57811'; fetch(api) .then(response => response.json()) .then(displayMenu); }; fetchAndDisplayMenu() 

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