skip to Main Content

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


  1. 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 treats brand as a string and literally try searching for a brand named brand.

    Since you are looping through the brand name in the array, you only know the actual brand like NewBalance or Adidas in the runtime so you need to use the Bracket Notation Brands[brand] so that brand is treated as a variable inside the bracket.

    <input type="checkbox" name={brand} className="cursor-pointer" checked={brandState.Brands[brand]} />
    
    Login or Signup to reply.
  2. 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>
      )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search