I am trying to get the nested array from a input value of a checkbox. How do I handle a nested array?
These are the values:
const othersOptions = [
{procedure:'ORAL PROPHYLAXIS',price: 1000},
{procedure:'TOOTH RESTORATION',price:1200},
{procedure:'TOOTH EXTRACTION',price:800}
];
This is how I get the values from checkbox. I am guessing that value={[item]}
is procedure:'ORAL PROPHYLAXIS',price: 1000
if the ORAL PROPHYLAXIS checkbox is checked
<Form>
{othersOptions.map((item, index) => (
<div key={index} className="mb-3">
<Form.Check
value={[item]}
id={[item.procedure]}
type="checkbox"
label={`${item.procedure}`}
onClick={handleChangeCheckbox('Others')}
required
/>
</div>
))}
</Form>
When I console.log the value it shows that the value is [Object object] this is the value
.
const handleChangeCheckbox = input => event => {
var value = event.target.value;
console.log(value, "this is the value")
var isChecked = event.target.checked;
setChecked(current =>
current.map(obj => {
if (obj.option === input) {
if(isChecked){
return {...obj, chosen: [{...obj.chosen, value}] };
}else{
var newArr = obj.chosen;
var index = newArr.indexOf(event.target.value);
newArr.splice(index, 1);
return {...obj, chosen: newArr};
}
}
return obj;
}),
);
console.log(checked);
}
and this is how I save the nested array:
const [checked, setChecked] = useState([
{ option: 'Others',
chosen: [],
]);
The reason why I need the procedure and price is so that I can save the values to MongoDB and get the values to another page which is a Create Receipt page. I want the following procedures price to automatically display in the Create Receipt page.Thank you for the help!
CodePudding user response:
Don't need to use the arrays as values. just keep it as objects
value={item}
id={item.procedure}
CodePudding user response:
You can JSON.stringify
the value for the option:
<Form.Check
value={JSON.stringify([item])}
...
...
/>
And then JSON.parse
when setting it to your nested map.
const handleChangeCheckbox = (input) => (event) => {
var value = JSON.parse(event.target.value);
...
...
}
Working Demo:
Another way
Or else you can use index of the map as the value and lookup from the map again.