1

I am using themealdb.com API & it gives you the ingredients like this:

"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": "",

I am fetching from the API & then using React Hooks to set an object with all recipe attributes. For the ingredients I want something like this: [Quinoa, Butter, Red Chili ...].

How do I loop through the JSON & find the keys that match "strIngredient" & and not empty strings & then add them to an array?

Thank you!

Diarrah
  • 125
  • 1
  • 8
  • Does this answer your question? [How to get all properties values of a JavaScript Object (without knowing the keys)?](https://stackoverflow.com/questions/7306669/how-to-get-all-properties-values-of-a-javascript-object-without-knowing-the-key) – Heretic Monkey Oct 25 '20 at 19:01

2 Answers2

1

let say your data is stored in a variable called mydata then you can do it like:

let newArray = [];

for (const key of Object.keys(mydata)) {
    if (key.includes('strIngredient') && mydata[key] !== "") {             
        newArray.push(mydata[key]) 
    }
}
Raghav Garg
  • 3,601
  • 2
  • 23
  • 32
webcoder
  • 1,331
  • 1
  • 9
  • 27
  • OP is looking for conditional appending. First that the key name includes `strIngredient` and that the value is not empty. Right now what you have is the equivalent of `Object.values` – Andrew Oct 24 '20 at 02:12
0
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
}
Diarrah
  • 125
  • 1
  • 8