解构从API获取的数组对象

时间:2019-07-04 09:35:26

标签: javascript

我要执行的任务是使用网址https://randomapi.com/api/d12c99b82acfefae33f7ce9239b57811从API中获取数组对象,并且我需要对数组进行解构,并将该数组中的结果值仅分配给代码中的变量数据。 这是我尝试过的示例

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();
                });
        };

它带来了您要解构的数组未迭代的错误?

正在从API提取的对象看起来像这样

{
  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
    }
  }
};

1 个答案:

答案 0 :(得分:3)

您收到此错误的原因有两个:

  1. results[1]不存在
  2. 您没有将任何参数传递给displayMenu(),因此您一开始就没有要使用的数据。

您应该这样编写代码:

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()