How to make an array unique by object key? I have dynamic checkboxes, whose id I put in the state.
In the format [checkBoxId]: e.target.value
And then I try to make a unique array from the received checked from the checkbox, but nothing comes out
[...new Map(
myCheckboxes.map((item) => { // item {dfsd34534ftg: true} (dfsd34534ftg - id)
const key = Object.keys(item);
return [item[key], item];
}),
).values()]
{response.map(({ id}, idx) => (
<div key={id}>
<Checkbox
change={e => {
setMyCheckboxes(prev => [
...prev,
{
[id]: e.target.checked,
},
]);
}}
checked={myCheckboxes[idx]?.id}
/>
...
CodePudding user response:
Object.keys(item)
returns Array
, which you trying to use as key. You need to extract key from this array in order to make it work as you want:
const key = Object.keys(item)[0];
return [item[key], item];
CodePudding user response:
Firstly, you need to declare your checkboxes' state
const [myCheckboxes, setMyCheckboxes] = useState({}) //define a map
And then you can call setMyCheckboxes
on change
event like below
{response.map(({ id }, idx) => (
<div key={id}>
<Checkbox
change={e => {
setMyCheckboxes(prev => ({
...prev,
[id]: e.target.checked,
}));
}}
checked={myCheckboxes?.id}
/>
...