我正在使用themealdb.comAPI,它为您提供了如下成分:"strIngredient1": "Quinoa","strIngredient2": "Butter","strIngredient3": "Red Chilli","strIngredient4": "Garlic","strIngredient5": "Chicken Breast","strIngredient6": "Olive Oil","strIngredient7": "Black Olives","strIngredient8": "Red Onions","strIngredient9": "Feta","strIngredient10": "Mint","strIngredient11": "Lemon","strIngredient12": "","strIngredient13": "","strIngredient14": "","strIngredient15": "","strIngredient16": "","strIngredient17": "","strIngredient18": "","strIngredient19": "","strIngredient20": "",我正在从 API 获取数据,然后使用 React Hooks 设置一个具有所有配方属性的对象。对于成分,我想要这样的东西:[Quinoa, Butter, Red Chili ...]。如何遍历 JSON 并找到匹配"strIngredient"& 而不是空字符串的键,然后将它们添加到数组中?谢谢你!
2 回答
长风秋雁
TA贡献1757条经验 获得超7个赞
假设您的数据存储在一个名为的变量中,mydata那么您可以这样做:
let newArray = [];
for (const key of Object.keys(mydata)) {
if (key.includes('strIngredient') && mydata[key] !== "") {
newArray.push(mydata[key])
}
}
守着一只汪
TA贡献1872条经验 获得超3个赞
const getIngredients = (strIngredients) => {
let ingredients = [];
Object.entries(strIngredients).map(i => {
const [key, value] = i;
if (key.includes('strIngredient') && value) {
ingredients.push(value)
} else return
})
return ingredients
}
添加回答
举报
0/150
提交
取消