【问题标题】:How do I make an array from a JSON object that matches a certain key?如何从与某个键匹配的 JSON 对象创建一个数组?
【发布时间】:2021-02-07 01:25:14
【问题描述】:

我正在使用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 设置具有所有配方属性的对象。对于我想要这样的成分:[Quinoa, Butter, Red Chili ...].

如何遍历 JSON 并找到匹配 "strIngredient" & 而不是空字符串的键,然后将它们添加到数组中?

谢谢!

【问题讨论】:

标签: javascript html json reactjs api


【解决方案1】:

假设您的数据存储在一个名为 mydata 的变量中,那么您可以这样做:

let newArray = [];

for (const key of Object.keys(mydata)) {
    if (key.includes('strIngredient') && mydata[key] !== "") {             
        newArray.push(mydata[key]) 
    }
}

【讨论】:

  • OP 正在寻找条件附加。首先,键名包含strIngredient,并且值不为空。现在你拥有的相当于Object.values
【解决方案2】:
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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 2021-12-24
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多