Setting nested object value in session storage
Asked Answered
V

3

6

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')
Void answered 26/9, 2018 at 21:31 Comment(0)
M
5

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.

Murillo answered 26/9, 2018 at 21:38 Comment(4)
LOL! Upvoted for beating me by 20 seconds; same as @SteveArcher. This is a good answer and the same as I would have suggested.Eld
@SteveArcher sorry. Next time, maybe!Murillo
@Anovative Ditto.Murillo
Thank you both for you time , makes sense and worked great.Void
H
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))
Humberto answered 26/9, 2018 at 21:39 Comment(0)
G
0

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));
Garrik answered 8/3, 2022 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.