简体   繁体   English

如果输入值与不同数组中的一个值匹配,请检查复选框列表

[英]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".我有一个对象数组(array1),我正在循环并以表格形式呈现为 type="checkbox" 的一系列输入。 I am setting the input value to the object.id, and the input name to the object.name.我将输入值设置为 object.id,并将输入名称设置为 object.name。

I then have a second array (array2), which is just an array of values.然后我有第二个数组(array2),它只是一个值数组。 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."我需要将array1 与array2 进行比较,如果给定输入的值与array2 中的值之一匹配,则设置checked="true"。 If not, then do not check.如果不是,则不要检查。 It's basically auto-checking any inputs that already have a value that exists in array2.它基本上是自动检查任何已经具有存在于 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 :您可以通过Array.mapArray.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 .您可以 map array1到复选框输入,并简单检查array2是否包含来自array1元素的id属性。

{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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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