简体   繁体   中英

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"} ] .

I'm also having another array with few values like 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. In this case Mr.Z should be checked by default and other two should be unchecked.

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

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