小唯快跑啊
2023-06-09 10:47:20
我正在使用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條經驗 獲得超4個贊
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
提交
取消