【问题标题】:How do I loop through data from an API in Javascript?如何在 Javascript 中循环访问来自 API 的数据?
【发布时间】:2021-03-27 11:41:11
【问题描述】:

我正在尝试学习如何将数据从 API 获取到 JSON 数据的多个级别,但我对如何做到这一点感到困惑。例如,我正在尝试创建一个随机膳食生成器,它显示一组食谱中的成分列表,而且我需要的成分名称在它们自己的对象中。

我不知道如何设置我的循环以遍历列表并获取成分名称以显示它。到目前为止,这是我的示例:codepen

谢谢!

document.getElementById("shuffle").addEventListener('click', getImage);


async function getImage() {
const response = await fetch("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/random?number=1", {
    "method": "GET",
    "headers": {
        "x-rapidapi-key": "{redacted}",
        "x-rapidapi-host": "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com"
    }
})
const data = await response.json();
  document.getElementById('title').innerHTML = data.recipes[0]["title"];
  document.getElementById('instructions').innerHTML = data.recipes[0]["instructions"];
  document.getElementById('image').src = data.recipes[0]["image"];
  show(data); 
}

 getImage()
 .catch(error => {
    console.error(error);
    });


function show(data) { 
  let list = 
      `
      <ul></ul>
      `
    for (let ingredient of data.recipes) { 
        list += `  
    <li>${ingredient.extendedIngredients[0].originalString}</li>        
`; 
    }
  
  document.getElementById('ingredients').innerHTML = list;
} 
.recipe {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
}
.recipe__directions {
  display: flex;
  width: 50vw;
  margin: 2rem;
}
.recipe__instructions {
  text-align: left;
  margin-right: 1rem;
}
.recipe__image {
  width: 25vw;
  margin-left: 1rem;
}
<html>
  <head>
    <!-- Material Design Lite -->
    <script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
    <!-- Material Design icon font -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  </head>
  <body>
    <section class="recipe">
      <h1>Feeling hungry?</h1>
      <h2>Get a random meal by clicking below</h2>
      <button class="button mdl-button mdl-js-button mdl-button--raised mdl-button--colored" id="shuffle">Find a meal</button>
      <h3 id="title" class="recipe__title"></h3>
      <div id="ingredients" class="recipe__ingredients"></div>
      
      <div class="recipe__directions">
        <p id="instructions" class="recipe__instructions"></p>
        <img id="image" class="recipe__image" src="" alt="">
      </div>
    </section>
  </body>
</html>

【问题讨论】:

  • 代码看起来已经很不错了,但是如果没有看到来自 API 的示例响应,很难说出您需要做什么。
  • (一般来说,在互联网上发布 API 密钥并不是一个好主意。)

标签: javascript arrays json for-loop object


【解决方案1】:
  • 如果你看一下 json 结构,你会发现extendedIngredients 是一个数组,所以你可以循环遍历它们中的每一个
  • 您一次只能获得一个食谱,因此无需循环...

您可以将循环更改为:

   for (let ingredient of data.recipes[0].extendedIngredients) { // loop over ingredients of first recipe
            list += `  
        <li>${ingredient.originalString}</li>        
    `; 
        }

document.getElementById("shuffle").addEventListener('click', getImage);


async function getImage() {
const response = await fetch("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/random?number=1", {
    "method": "GET",
    "headers": {
        "x-rapidapi-key": "",
        "x-rapidapi-host": ""
    }
})
const data = await response.json();
  document.getElementById('title').innerHTML = data.recipes[0]["title"];
  document.getElementById('instructions').innerHTML = data.recipes[0]["instructions"];
  document.getElementById('image').src = data.recipes[0]["image"];
  show(data); 
}

 getImage()
 .catch(error => {
    console.error(error);
    });


function show(data) { 
  let list = 
      `
      <ul></ul>
      `
    for (let ingredient of data.recipes[0].extendedIngredients) { // loop over ingredients of first recipe
        list += `  
    <li>${ingredient.originalString}</li>        
`; 
    }
  
  document.getElementById('ingredients').innerHTML = list;
} 
.recipe {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
}
.recipe__directions {
  display: flex;
  width: 50vw;
  margin: 2rem;
}
.recipe__instructions {
  text-align: left;
  margin-right: 1rem;
}
.recipe__image {
  width: 25vw;
  margin-left: 1rem;
}
<html>
  <head>
    <!-- Material Design Lite -->
    <script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
    <!-- Material Design icon font -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  </head>
  <body>
    <section class="recipe">
      <h1>Feeling hungry?</h1>
      <h2>Get a random meal by clicking below</h2>
      <button class="button mdl-button mdl-js-button mdl-button--raised mdl-button--colored" id="shuffle">Find a meal</button>
      <h3 id="title" class="recipe__title"></h3>
      <div id="ingredients" class="recipe__ingredients"></div>
      
      <div class="recipe__directions">
        <p id="instructions" class="recipe__instructions"></p>
        <img id="image" class="recipe__image" src="" alt="">
      </div>
    </section>
  </body>
</html>

【讨论】:

    【解决方案2】:

    使用forEach() 循环遍历每个extendedIngredients 属性。

    function show(data) { 
      let list = 
          `
          <ul></ul>
          `
      data.recipes[0].extendedIngredients.forEach( function(ingredient){
            list += `  
        <li>${ingredient.originalString}</li>        
    `; 
        });
      
      document.getElementById('ingredients').innerHTML = list;
    } 
    

    你在正确的轨道上,但还不够深入。您编写的 for 循环遍历每个 recipes,而不是每个 extendedIngredients。只有一个recipes,因此您可以使用密钥[0] 访问它。

    function show(data) { 
      let list = 
          `
          <ul></ul>
          `
        for (let ingredient of data.recipes[0].extendedIngredients) { 
            list += `  
        <li>${ingredient.originalString}</li>        
    `; 
        }
      
      document.getElementById('ingredients').innerHTML = list;
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2015-11-22
      • 2021-09-27
      • 1970-01-01
      • 2018-06-24
      • 2011-12-10
      • 2013-07-03
      相关资源
      最近更新 更多