Advertisements
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
>Solution :
Alternatively to Sherry Hsu’s excelent suggestion, you can loop over entries instead of keys:
Object.entries(brandState.Brands).map([brand, checked]=>
<div className="">
<label htmlFor={brand} className="mr-[10px]">{brand}: </label>
<input type="checkbox" name={brand} className="cursor-pointer" checked={checked}/>
</div>
)