I have an array of the following type retrieved from an API
{
strIngredient1: "Chicken"
strIngredient2: "Onion"
strIngredient3: "Tomatoes"
strIngredient4: ""
strIngredient5: ""
strIngredient6: ""
strMeasure1: 1lb
strMeasure2: 2
strMeasure3: 3
strMeasure4: ""
strMeasure5: ""
strMeasure6: ""
}
And I need to filter out the ingredients and measures which are not null and combine those in the format of ingredients-measure (eg. Chicken – 1lb).
I tried using the filter and map on the object as below
const validIngredients = Object.keys(singleRecipe)
.filter((item) => {
if (item.startsWith("strIngredient") && singleRecipe[item] !== "") {
return item;
}
if (item.startsWith("strMeasure") && singleRecipe[item] !== "") {
return item;
}
})
.map((key) => singleRecipe[key]);
and was able to retrieve the values which are not null in the below format in the console
(6)["Chicken","Onion","Tomatoes","1lb","2","3"].
I’m not able to figure out how to concatenate the values. Any suggestions for retrieving these values differently?
2
Answers
Map will return an array, you just mapped from key to values.
You should remove the map function, and in new line will combine the ingredient to the measurement.
To concatenate the ingredients and measures in the desired format, you can modify your code slightly. Instead of filtering and mapping separately, you can perform both operations within a single reduce function. Here’s how you can do it:
In this code, we use reduce to iterate over the keys of the singleRecipe object. For each key that starts with "strIngredient" and has a non-empty value, we check if there’s a corresponding measure with a non-empty value. If so, we concatenate the ingredient and measure with a hyphen and push it to the result array. Otherwise, we only push the ingredient value to the array. Finally, we get the desired format for valid ingredients and measures.