How do I get a get a value from object key when looping through it.
I currently have an object like this:
const [brandState,setBrandState] = useState({
Brands:{
NewBalance: false,
Nike: false,
Addiddas: false,
Converse:false,
UnderArmour:false,
},
});
And I am looping through it rendering checkbox inputs like this:
{
Object.keys(brandState.Brands).map((brand)=>
<div className="">
<label htmlFor={brand} className="mr-[10px]">{brand}: </label>
<input type="checkbox" name={brand} className="cursor-pointer" />
</div>
)
}
Everything workouts apart from getting the value (true or false)
I tried setting checked={brand}
but I get an error saying that brand is a string, I also tried checked={brandState.Brands.brand}
however that also gives me an error.
How can I get the value of each key to set as the checked?
Thanks
2
Answers
You need to set the value of the checkbox to be the value of each key in Brands. i.e.
Brands[brand]
If you access the value via dot notation,
Brands.brand
, it treatsbrand
as a string and literally try searching for a brand namedbrand
.Since you are looping through the brand name in the array, you only know the actual brand like
NewBalance
orAdidas
in the runtime so you need to use the Bracket NotationBrands[brand]
so thatbrand
is treated as a variable inside the bracket.Alternatively to Sherry Hsu’s excelent suggestion, you can loop over entries instead of keys: