JavaScript. Как получить массив из значений свойств обьекта при работе с API?
Есть результат от вызова API (ниже).
Необходимо получить массив со значений свойств обьекта под названием "strIngredient" (в данном случае чтобы было так - ["Gin","Grand Marnier","Lemon Juice","Grenadine"]). Было бы просто перебрать обьект оычным for in-ом, но задачу усложняет то что эти свойства пронумерованы (strIngredient1, strIngredient2 и т.д.). Подскажите пожалуйста лучшую практику в данном случае, чтобы не пилить индусский код.
{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
Ответы (2 шт):
Автор решения: Vadim
→ Ссылка
На ноде собрал, думаю это идеальный вариант для тебя. Там 15 ингредиентов+пропорций всего(насколько я вижу, из пары-тройки респонсов - апи курильщика)
const fetch = require('node-fetch');
(async()=>{
// let r = await fetch('https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=17222').then((res)=>(res.json()));
let r = await fetch('https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=17223').then((res)=>(res.json()));
r = r.drinks[0];
let arr = [];
for(let i=1; i < 16; i++){
if(r[`strIngredient${i}`] === null)continue;
arr.push({[r[`strIngredient${i}`]]: r[`strMeasure${i}`]});
}
console.log(r.strDrink);
console.log(arr);
})();
Автор решения: Eugene Adams
→ Ссылка
решение в контексте конкретной задачи:
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);
}
}
};