'Setting nested object value in session storage
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')
Solution 1:[1]
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))
Solution 2:[2]
If you get an error, that it cannot be added to null
Instead ibrahim mahrir's answer:
var projectInfo = JSON.parse(sessionStorage.getItem('projectInfo'));
projectInfo.project1.name = 'Student Fund raiser';
sessionStorage.setItem('projectInfo', JSON.stringify(projectInfo));
Try this:
var projectInfo = JSON.parse(sessionStorage.getItem('projectInfo'));
projectInfo = projectInfo === null ? {} : projectInfo;
projectInfo.project1.name = 'Student Fund raiser';
sessionStorage.setItem('projectInfo', JSON.stringify(projectInfo));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Steve Archer |
| Solution 2 | AndyNope |
