Im building a recipe app that takes external api data and displays it on the page. I wanted to know if there was a way to check all the key names in the object for a certain string "strIngredient..." and display all the values that contain the key name "strIngredient..."
this is my drinks.js component
import React from "react";
function Drinks({ drinkList }) {
if (!drinkList) return <></>;
return (
<section className="drinkCard">
<h1 className="drinks-name">{drinkList.drinks[0].strDrink}</h1>
<img src={drinkList.drinks[0].strDrinkThumb} alt="Drink" />
<p>
<strong>Category: </strong>
{drinkList.drinks[0].strCategory}
</p>
<p>
<strong>Alcoholic: </strong>
{drinkList.drinks[0].strAlcoholic}
</p>
<p>
<strong>Instructions: </strong>
{drinkList.drinks[0].strInstructions}
</p>
<ol>{showIngredientsList()}</ol>
</section>
);
}
export default Drinks;
and here is a picture of the JSON data (I want to only retrieve the values of the ones with key name containing "strIngredient") :
CodePudding user response:
About the logics, you can do something like this then
for (const property in drinkList?.drink[0]) {
// property would be the key
// drinkList?.drink[0][property] would be the value
// console log value that have key 'strIngredient'
property.include('strIngredient') && console.log(drinkList?.drink[0][property])
}
CodePudding user response:
You can achieve this by mapping the array and using Object.entries
on each object to be able to filter the resulting array of [key, value]
by their keys, then merge it back to an object.
var drinks = [{
idDrink: "11000",
strDrink: "Mojito",
strDrinkAlternative: null,
strTags: "IBA,ContenporaryClassic,Alcohol",
strVideo: null,
strInstructions: "Muddle mint leaves with sugar and...",
strInstructionsES: "Muddle mint leaves with sugar and...",
strInstructionsDE: "Muddle mint leaves with sugar and...",
strIngredient1: "Light rum",
strIngredient2: "Lime",
strIngredient3: "Sugar",
strIngredient4: "Mint",
strIngredient5: "Soda Water",
strIngredient6: null,
strIngredient7: null,
strIngredient8: null,
}];
var filteredDrinks = drinks.map((drink) =>
Object.fromEntries(
Object.entries(drink).filter(([key, _value]) =>
key.includes('strIngredient')
)
)
);
// to get only the values of `strIngredients*`:
var filteredDrinksValues = drinks.map((drink) =>
Object.entries(drink)
.filter(([key, _value]) => key.includes('strIngredient'))
.map(([_key, value]) => value)
);