简体   繁体   English

将数组中的数据显示到复选框中,这样如果相同的数据在另一个数组中,它将显示在 React 中选中的复选框

[英]Show data from array into checkbox such that If the same data is in another array, it will show checkbox as checked in React

I have an array containing all values let say arr1 = [{"Name":"Mr.X"},{"Name":"Mr.Y"},{"Name":"Mr.Z"} ] .我有一个包含所有值的数组,比如说arr1 = [{"Name":"Mr.X"},{"Name":"Mr.Y"},{"Name":"Mr.Z"} ]

I'm also having another array with few values like arr2 = [{"Name":"Mr.Z"}] .我还有另一个数组,其中的值很少,例如arr2 = [{"Name":"Mr.Z"}]

I want to show all the data from arr1 as checkbox such that if the data exist in arr2, it will show as a checked checkedbox.我想将 arr1 中的所有数据显示为复选框,这样如果数据存在于 arr2 中,它将显示为选中的复选框。 In this case Mr.Z should be checked by default and other two should be unchecked.在这种情况下,默认情况下应选中 Mr.Z,而应取消选中其他两个。

I have tried this but my data is now showing multiple times due to two loops.我已经尝试过了,但由于两个循环,我的数据现在显示多次。

{arr1.map((name1) =>
    arr2.map((name2) =>
    name1.Name === name2.Name ? (
        <FormControlLabel
             control={
                 <Checkbox
                     checked={true}
                     name="Name"
                     color="primary"
                     disabled={editable}
                 />
             }
             label={name.Name}
        />
        ) : (
            <FormControlLabel
                 control={
                     <Checkbox
                          name="Name"
                          color="primary"
                          disabled={editable}
                    />
                 }
                 label={name.Name}
            />
      )
))}

Please let me know what approach should i apply?请让我知道我应该采用什么方法?

Try something among the lines of:尝试以下方法:

arr1.map((arrItem) =>
        (
            (arr2.find(u => u.Name === arrItem.Name)) ?
            console.log(arrItem.Name + " checked")
            :
            console.log(arrItem.Name + " unchecked")
        ))

When given your input, this produces: output当给定您的输入时,这会产生: output

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

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