'How to rename objects in array?
I am trying to use this API however, I want to use a for loop or map through the strMeasure & strIngredient. Currently those have numbers less than 20 attached. So I am thinking I need to make an array first using a for loop and then implement it? Let me know your thoughts..
const [recipeData, setRecipeData] = useState([]);
const ingredientList = recipeData.map((allData) => {
const arr = [];
for (let i = 1; i <= 20; i++) {
arr.push(allData[`strMeasure${i}`] + " " + allData[`strIngredient${i}`]);
}
return arr;
});
But then do not know how to inject this in my component.
Cheers!
Solution 1:[1]
Instead of jointing them to a string, I would suggest storing them as key, value pairs within an object. This way it is easier to access the values in your UI.
const allData = {
strIngredient1: "Beef",
strIngredient2: "Plain Flour",
strMeasure1: "1kg",
strMeasure2: "2 tbs",
…
};
const items = [];
for (let i = 1; i <= 20; i += 1) {
const strIngredient = allData[`strIngredient${i}`];
const strMeasure = allData[`strMeasure${i}`];
items.push({
ingredient: strIngredient,
measure: strMeasure,
});
}
// const items = [
// {
// ingredient: "Beef",
// measure: "1kg",
// },
// …
// ];
After you transformed your data, you can pass it easily to your component
function Recipe(props) {
const { items } = props.items;
return (
<ul>
{items.map((item) => (
<li key={item.ingredient}>
{item.ingredient}: {item.measure}
</li>
))}
</ul>
);
}
<Recipe items={items} />;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

