Hi everyone having a tough time updating a value that I am storing in sessionstorage. I tried a few ways to target the nested objects values with no luck. Any help would be greatly appreciated.
Object I am creating in JavaScript
var projectInfo = {
project1: {
name: 'Unique name',
extraCredit: true
}
project2: {
name: 'Unique name',
extraCredit: true
}
}
How I am persisting to session
sessionStorage.setItem('projectInfo', JSON.stringify(projectInfo));
How do I target the nested project name in project info. For example
sessionStorage.setItem(projectInfo.project1.name, 'Student Fund raiser')
The getItem() method returns value of the specified Storage Object item. The getItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorage object.
You can store the value in localStorage with the key value pair. It has two methods setItem(key, value) to store the value in the storage object and getItem(key) to retrieve the value from the storage object. document. getElementById("result").
You can't do it like that. You have to retrieve the whole object, parse it, change what you want and then put it back into the storage:
var projectInfo = JSON.parse(sessionStorage.getItem('projectInfo'));
projectInfo.project1.name = 'Student Fund raiser';
sessionStorage.setItem('projectInfo', JSON.stringify(projectInfo));
Note: You might as well check if sessionStorage.getItem
returns something in case the object is not stored yet.
You can't change the value of the nested item while it's stringified (Well, I suppose you theoretically could by parsing the string yourself somehow, but that sounds like a real chore). I think the best approach is to retrieve the string, parse it back to a JS object, set the value, re-stringify it, then store it.
var projectString = sessionStorage.getItem('projectInfo')
var projectObject = JSON.parse(projectString)
projectObject.project1.name = 'Student Fund raiser'
sessionStorage.setItem(JSON.stringify(projectObject))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With