JavaScript. How do you get a mass of the enclave properties in API?
-
There's a result of the API challenge.
There's a need to get a lot of objects called "strIngredient." It would be simple to remove the cult from the ordinary for in-, but the challenge complicates that these properties are numbered (strIngredient1, strIngredient2, etc.). Please indicate the best practice in this case so as not to write the Hindu code.
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …} config: {url: "https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=17222", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} data: drinks: Array(1) 0: dateModified: "2017-09-07 21:42:09" idDrink: "17222" strAlcoholic: "Alcoholic" strCategory: "Cocktail" strCreativeCommonsConfirmed: "No" strDrink: "A1" strDrinkAlternate: null strDrinkDE: null strDrinkES: null strDrinkFR: null strDrinkThumb: "https://www.thecocktaildb.com/images/media/drink/2x8thr1504816928.jpg" strDrinkZH-HANS: null strDrinkZH-HANT: null strGlass: "Cocktail glass" strIBA: null strIngredient1: "Gin" strIngredient2: "Grand Marnier" strIngredient3: "Lemon Juice" strIngredient4: "Grenadine" strIngredient5: null strIngredient6: null strIngredient7: null strIngredient8: null strIngredient9: null strIngredient10: null strIngredient11: null strIngredient12: null strIngredient13: null strIngredient14: null strIngredient15: null strInstructions: "Pour all ingredients into a cocktail shaker, mix and serve over ice into a chilled glass." strInstructionsDE: "Alle Zutaten in einen Cocktailshaker geben, mischen und über Eis in ein gekühltes Glas servieren." strInstructionsES: null strInstructionsFR: null strInstructionsZH-HANS: null strInstructionsZH-HANT: null strMeasure1: "1 3/4 shot " strMeasure2: "1 Shot " strMeasure3: "1/4 Shot" strMeasure4: "1/8 Shot" strMeasure5: null strMeasure6: null strMeasure7: null strMeasure8: null strMeasure9: null strMeasure10: null strMeasure11: null strMeasure12: null strMeasure13: null strMeasure14: null strMeasure15: null strTags: null strVideo: null __proto__: Object length: 1 __proto__: Array(0) __proto__: Object headers: {content-type: "application/json"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "" __proto__: Object
-
Addressing the specific objective:
import axios from 'axios';
export default class Drink { constructor(id) { this.id = id; }
async getResults() { try { const res = await axios(`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${this.id}`); console.log(res); const drinksObj = res.data.drinks[0]; this.title = drinksObj.strDrink; this.category = drinksObj.strCategory; this.img = drinksObj.strDrinkThumb; this.ingredients = []; for (let key in drinksObj) { if (key.includes('strIngredient') && drinksObj[key] !== null) { this.ingredients.push(drinksObj[key]); } } } catch(error) { alert(error); } }
};