我正在使用cocktaildb API,并尝试提取成分并将其输出到页面上。
他们提供的 JSON 将成分列出为
strIngredient1:"Lager"
strIngredient2:"Tequila"
strIngredient3:""
...
strIngredient15:""
我一直在试图弄清楚如何制作它,以便它可以循环遍历或将 strIngredient1-15 分组为 strIngredient,这样我就可以拥有一个仅包含成分的数组,并过滤掉 strIngredient 是否为空。 我还想让它们按顺序排列,这样当我将其与测量值相匹配时,它就会有意义。
strMeasure1:"16 oz "
strMeasure2:"1.5 oz"
strMeasure3:""
...
strMeasure4:""
最佳答案
我想说我喜欢你对 API 的品味!
测试玛格丽塔:
https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita '
调用此函数将给出一个 JSON 数组(结果),我们可以像这样解析它:
if (!result || !result.drinks || result.drinks.length <= 0) {
console.log('No drinks found!!');
return;
}
// Get the first drink.
var drink = result.drinks[0];
let index = 1;
let ingredientArray = [];
while (drink['strIngredient' + index]) {
ingredientArray.push({name: drink['strIngredient' + index], amount: drink['strMeasure' + index] ? drink['strMeasure' + index]: "A dash "});
index++;
}
console.log('Drink: ', drink.strDrink);
console.log('Ingredients: ');
ingredientArray.forEach((ingredient) => {
console.log(`${ingredient.amount} of ${ingredient.name}`)
});
我得到结果:
Drink: Margarita
Ingredients:
1 1/2 oz of Tequila
1/2 oz of Triple sec
1 oz of Lime juice
A dash of Salt
要在 HTML 页面中显示,我们可以使用类似的代码(两个文件:test.html 和 app.js):
Test.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="app.js"></script>
</head>
<body topmargin="40" leftmargin="40" onLoad="downloadCocktail()">
<div id="result">Loading..</div>
</br>
<button onClick="downloadCocktail()">Download cocktail</button> : <input type="text" id="cocktail" value="Margarita"><br>
</body>
</html>
并且在同一目录中:
app.js
function outputDrink(drink)
{
console.log(drink);
let index = 1;
let ingredientArray = [];
while (drink['strIngredient' + index]) {
ingredientArray.push({name: drink['strIngredient' + index], amount: (drink['strMeasure' + index]||'').trim() ? drink['strMeasure' + index]: "A dash "});
index++;
}
var text = '';
text += `<b>Drink: </b><br/>${drink.strDrink}<br/><br/>`;
text += `<b>Glass: </b><br/>${drink.strGlass}<br/><br/>`;
text += '<b>Ingredients:</b></br>';
ingredientArray.forEach((ingredient) => {
text += `<li>${ingredient.amount} of ${ingredient.name}</li>`;
});
text += `</br><b>Instructions: </b></br>${drink.strInstructions}<br/>`;
$( "#result" ).html(text);
}
function downloadCocktail(){
let cocktailName = $('#cocktail').val();
console.log('Downloading details for: ', cocktailName);
var cocktail = encodeURIComponent(cocktailName);
$.ajax({
type: 'GET',
url: 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s=' + cocktail,
timeout:5000,
crossDomain: true,
dataType:'json',
success: function(result, status){
if (!result.drinks || result.drinks.length <= 0) {
$( "#result" ).html('No drinks found!!');
return;
}
// Get the first drink.
var drink = result.drinks[0];
outputDrink(drink);
},
error: function (errorMessage) {
console.error(errorMessage);
}
});
}
您的页面将如下所示:
饮料:玛格丽塔
玻璃:鸡尾酒杯
成分:
- 1 1/2 盎司龙舌兰酒
- 1/2 盎司三秒
- 1 盎司青柠汁
- 少许盐
项目目录:
\
- test.html
- 应用程序.js
此外,您还可以输入您想要的鸡尾酒,点击下载获取配料。
干杯!!
关于javascript - 如何使用类似的 prop 通过 API 返回的 JSON 进行过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49580528/