Push objects into an array programatically

I am Building a simple recipes app and I am fetching the recipes from an API.

I am having a little bit of trouble with the ingredients and their measures.

This is what I am getting from the API:

(You can use postman or something similar to see the data from this link https://www.themealdb.com/api/json/v1/1/lookup.php?i=52773)

            "strIngredient1": "Salmon",
            "strIngredient2": "Olive oil",
            "strIngredient3": "Soy Sauce",
            "strIngredient4": "Sake",
            "strIngredient5": "Sesame Seed",
            "strIngredient6": "",
            "strIngredient7": "",
            "strIngredient8": "",
            "strIngredient9": "",
            "strIngredient10": "",
            "strIngredient11": "",
            "strIngredient12": "",
            "strIngredient13": "",
            "strIngredient14": "",
            "strIngredient15": "",
            "strIngredient16": null,
            "strIngredient17": null,
            "strIngredient18": null,
            "strIngredient19": null,
            "strIngredient20": null,
            "strMeasure1": "1 lb",
            "strMeasure2": "1 tablespoon",
            "strMeasure3": "2 tablespoons",
            "strMeasure4": "2 tablespoons",
            "strMeasure5": "4 tablespoons",
            "strMeasure6": "",
            "strMeasure7": "",
            "strMeasure8": "",
            "strMeasure9": "",
            "strMeasure10": "",
            "strMeasure11": "",
            "strMeasure12": "",
            "strMeasure13": "",
            "strMeasure14": "",
            "strMeasure15": "",
            "strMeasure16": null,
            "strMeasure17": null,
            "strMeasure18": null,
        "strMeasure19": null,
        "strMeasure20": null,  

How can I create an array from this data I am getting?

Ideally I would like to have an array like this [1 lb Salmon, 2 tablespoons Olive oil, 2 tablespoons Soy Sauce]…

Is there a good way to do this or do i have to hardcode it like this : [strIngredient1,StrMeasure1] etc…

which way is the best way to do this ?

Thank you in advance.

Answer

First I think the api should be fixed otherwise I see that there are only 20 ingredients allowed and they are matched with indexes; you can do something like this

const ingredients = [];

for(let i=1; i <= 20; i++ ) {
    if(data[`strMeasure${i}`]) {
        let item = [ data[`strMeasure${i}`] + " " +  data[`strIngredient${i}`]  ]
        ingredients.push(item)  
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *