Chan Sol Park
Chan Sol Park

Reputation: 11

How to filter through JSON return from API with similar prop?

I am using thecocktaildb API, and trying to pull the ingredients and output it on to the page.

The JSON they provide lists the ingredients as

strIngredient1:"Lager"
strIngredient2:"Tequila"
strIngredient3:""
...
strIngredient15:""

I have been trying to figure out how I can make it so it would loop through or group strIngredient1-15 to just strIngredients so I can have an array of just the ingredients, and filter out if the strIngredient is blank. I would also like to have them in order, so when I go to match it up with the Measurements, it would make sense.

strMeasure1:"16 oz "
strMeasure2:"1.5 oz"
strMeasure3:""
...
strMeasure4:""

Upvotes: 0

Views: 683

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

Let me say I like your taste in APIs!

Testing this for Margarita:

https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita'

Calling this will give a JSON array (result) which we can parse like so:

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

I get the result:

Drink:  Margarita
Ingredients:
1 1/2 oz  of Tequila
1/2 oz  of Triple sec
1 oz  of Lime juice
A dash  of Salt

To display in a HTML page we can use similar code (two files: test.html and 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>

And in the same directory:

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

Your page would look like so:

Drink: Margarita
Glass: Cocktail glass
Ingredients:

  • 1 1/2 oz of Tequila
  • 1/2 oz of Triple sec
  • 1 oz of Lime juice
  • A dash of Salt

Project directory:

\
- test.html
- app.js

In addition, you can enter the cocktail you want and click download to get the ingredients.

Cheers!!

Upvotes: 1

Related Questions