I am making an app in Svelte using TheCocktailDB's API. When it comes to listing measurements and ingredients, the JSON data looks something like this:
strIngredient1 "Tequila"
strIngredient2 "Triple sec"
strIngredient3 "Lime juice"
strIngredient4 "Salt"
strIngredient5 null
strIngredient6 null
strIngredient7 null
...and so on, up to 15.
Is there a best way in Svelte to run code that displays each of the fields that contain a value and ignores those with a null value?
CodePudding user response:
There is a nice tutorial I found on YouTube for Svelte Kit using this API. Basically you would want to map over the ingredients and measurements etc. Then filter the result.
Assuming saving the result to a variable called result
…
const result = await (
await fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
).json()
const ingredients = [...Array(15)]
.map((_value, i) => {
name: result.drinks[0][`strIngedient${i 1}`],
amount: result.drinks[0][`strMeasure${i 1}`]
}))
.filter((ingredient) => ingredient.name)
Now if ingredient.name
has a null value, it is filtered out of the array.
Now you could consume it like this in your template:
{#each ingredients as ingredient}
<--! Your markup here -->
<p>Ingredient: {ingredient.name} {ingredient.amount}</p>
{/each}
CodePudding user response:
There's probably not 'a best way' but different aproaches to get and display the ingredients with a value and their amount. This would be an alternative to the already given REPL
<script>
async function loadIngredients() {
const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
const result = await response.json()
const drink = result.drinks[0]
return Array.from({length:15}).reduce((ingredients, _, index) => {
const ingredient = drink[`strIngredient${index 1}`]
if(ingredient) {
ingredients.push({
name: ingredient,
amount: drink[`strMeasure${index 1}`]
})
}
return ingredients
},[])
}
</script>
{#await loadIngredients() then ingredients}
<ul>
{#each ingredients as ingredient}
<li>{ingredient.name} - {ingredient.amount}</li>
{/each}
</ul>
{/await}