简体   繁体   English

在 session 存储中设置嵌套的 object 值

[英]Setting nested object value in session storage

Hi everyone having a tough time updating a value that I am storing in sessionstorage.大家好,更新我存储在 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 Object 我在 JavaScript 创建

   var projectInfo = {
        project1: {
            name: 'Unique name',
            extraCredit: true
        }
        project2: {
            name: 'Unique name',
            extraCredit: true
        }
    }

How I am persisting to session我是如何坚持到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')

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. 注意:您还可以检查sessionStorage.getItem是否在尚未存储对象的情况下返回某些内容。

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. 我认为最好的方法是检索字符串,将其解析回JS对象,设置值,重新串行化,然后存储它。

var projectString = sessionStorage.getItem('projectInfo')
var projectObject = JSON.parse(projectString)
projectObject.project1.name = 'Student Fund raiser'
sessionStorage.setItem(JSON.stringify(projectObject))

If you get an error, that it cannot be added to null如果报错,说明无法添加到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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM