Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 489
Galactic Ranger Avatar asked Sep 26 '18 21:09

Galactic Ranger


People also ask

How do you find the value of an object in session storage?

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.

How do I store multiple values in session storage?

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").


2 Answers

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.

like image 95
ibrahim mahrir Avatar answered Sep 29 '22 19:09

ibrahim mahrir


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))
like image 38
Steve Archer Avatar answered Sep 29 '22 18:09

Steve Archer