[英]How do I make an array from a JSON object that matches a certain key?
我正在使用themealdb.com
API & 它給你這樣的成分:
"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 設置一個包含所有配方屬性的 object。 對於配料,我想要這樣的東西: [Quinoa, Butter, Red Chili...]
。
如何循環遍歷 JSON 並找到匹配"strIngredient"
而不是空字符串的鍵,然后將它們添加到數組中?
謝謝!
假設您的數據存儲在一個名為mydata
的變量中,那么您可以這樣做:
let newArray = [];
for (const key of Object.keys(mydata)) {
if (key.includes('strIngredient') && mydata[key] !== "") {
newArray.push(mydata[key])
}
}
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.