如何从匹配特定键的 JSON 对象创建数组?

我正在使用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"& 而不是空字符串的键,然后将它们添加到数组中?


谢谢你!


小唯快跑啊
浏览 136回答 2
2回答

长风秋雁

假设您的数据存储在一个名为的变量中,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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript