When I get results from an API with this function
let recipeArray = async function getRecipeByPreference() {
try {
let results = await axios.get('https://api.spoonacular.com/recipes/complexSearch?number=5&apiKey=*****', {
headers: {
"Content-Type": "application/json"
}
})
return recipeArray = results.data.results.slice(0, 5);
} catch (e) {
console.error(e);
}
}
These are the results returned in recipeArray:
0: {id: 716426, title: 'Cauliflower, Brown Rice, and Vegetable Fried Rice', image: 'https://spoonacular.com/recipeImages/716426-312x231.jpg', imageType: 'jpg'}
1: {id: 715594, title: 'Homemade Garlic and Basil French Fries', image: 'https://spoonacular.com/recipeImages/715594-312x231.jpg', imageType: 'jpg'}
2: {id: 715497, title: 'Berry Banana Breakfast Smoothie', image: 'https://spoonacular.com/recipeImages/715497-312x231.jpg', imageType: 'jpg'}
3: {id: 644387, title: 'Garlicky Kale', image: 'https://spoonacular.com/recipeImages/644387-312x231.jpg', imageType: 'jpg'}
4: {id: 716268, title: 'African Chicken Peanut Stew', image: 'https://spoonacular.com/recipeImages/716268-312x231.jpg', imageType: 'jpg'}
I want to put the first 5 ID numbers in the recipeArray, so I get this:
recipeArray = [716426,715594,715497,644387,716268]
and console.log(recipeArray[0]); will give me 716426
I know there are similar questions here on stack overflow but I can't make the solutions work for me.
Any help would be greatly appreciated!
Just change results.data.results.slice(0,5); to results.data.results.slice(0,5).map(({id})=> id); and it should work ;)
const results = [{
id: 716426,
title: 'Cauliflower, Brown Rice, and Vegetable Fried Rice',
image: 'https://spoonacular.com/recipeImages/716426-312x231.jpg',
imageType: 'jpg'
},
{
id: 715594,
title: 'Homemade Garlic and Basil French Fries',
image: 'https://spoonacular.com/recipeImages/715594-312x231.jpg',
imageType: 'jpg'
}, {
id: 715497,
title: 'Berry Banana Breakfast Smoothie',
image: 'https://spoonacular.com/recipeImages/715497-312x231.jpg',
imageType: 'jpg'
}, {
id: 644387,
title: 'Garlicky Kale',
image: 'https://spoonacular.com/recipeImages/644387-312x231.jpg',
imageType: 'jpg'
}, {
id: 716268,
title: 'African Chicken Peanut Stew',
image: 'https://spoonacular.com/recipeImages/716268-312x231.jpg',
imageType: 'jpg'
}
];
const idArray = results.slice(0, 5).map(({
id
}) => id);
console.log(idArray);
You could map the Array you got and make it only have the recipe Ids
return recipeArray = results.data.results.slice(0,5).map(elem => elem.id)
Map() is an Array method that changes the array to match the function passed, in our case we want to turn every recipe object into just its ID.