how to mutate nested object in javascript code example
Example 1: usestate nested object
const [currentApp, setCurrentApp] = useState({
userID: null,
hospitalName: null,
hospitalID: null,
date: null,
time: null,
timestamp: null,
slots: 1,
appointmentType: null
})
const [appointmentType, setAppointmentType] = useState({
Granulocytes: {
bloodType:null,
message: null
}
})
const handleGranChange = (e) => {
setAppointmentType({...appointmentType, Granulocytes : {
...appointmentType.Granulocytes,
[e.target.id] : e.target.value}
})
setCurrentApp({ ...currentApp, ['appointmentType'] : appointmentType })
console.log(currentApp)
}
Example 2: how to access nested objects in javascript
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"