简体   繁体   中英

Check a list of checkboxes if input value matches one of the values in different array

I have an array of objects (array1) that I am looping through and rendering in a form as a series of inputs where type="checkbox". I am setting the input value to the object.id, and the input name to the object.name.

I then have a second array (array2), which is just an array of values. I need to compare array1 to array2, and if the value for that given input matches one of the values in array2, then set checked="true." If not, then do not check. It's basically auto-checking any inputs that already have a value that exists in array2.

let array1 = [
{id: 28, name: "Action"}, 
{id: 35, name: "Comedy"},
{id: 80, name: "Crime"},
{id: 99, name: "Documentary"}
{id: 18, name: "Drama"}
{id: 10751, name: "Family"}
]

let array2 = [1, 65, 28, 12, 18]

Here's what I have for my loop:

for(let i in array2) {
   for(let j in array1) {
      if(array2[i] == array1[j].id) {
          return (
          <div>
             <label>name here</label>
             <input type="checkbox" id={array1[j].id} value={array1[j].id} name={array1[j].name} checked='true'/>
          </div>
          )
    }
      if(array2[i] != array1[j].id) {
           return (
           <div>
               <label>name here</label>
               <input type="checkbox" id={array1[j].id} value={array1[j].id} name={array1[j].name}/>
           </div>
          )
   }

Obviously this isn't working and sorry if my current code seems stupid. I've been at this for a while and I'm at a complete loss on how to make this work.

You could accomplish this via Array.map and Array.includes :

return array1.map(({id, name}) => (
  <input
    key={id}
    name={name}
    checked={array2.includes(id)}
  />
))

You can map array1 to the checkbox inputs and do a simple check that array2 includes the id property from elements in array1 .

{array1.map(({ id, name }) => (
  <label key={id}>
    {name}
    <input
      type="checkbox"
      value={id}
      name={name}
      defaultChecked={array2.includes(id)}
    />
  </label>
))}

编辑check-a-list-of-checkboxes-if-input-value-matches-one-of-the-values-in-different

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM