简体   繁体   中英

How can I store localStorage data in one object?

Now I got something like this, instead of creating new-info: {"name": "name", "description": "mydescription"} it deletes the previous new-info and just adds for example new-info: "test" How can I make this to be one object of values?

  function setName(value) {
      this.name = value
      localStorage.setItem('new-info', JSON.stringify(this.name))
    },
  function setDescription(value) {
      this.description = value
      localStorage.setItem('new-info', JSON.stringify(this.description))
    },

The issue appears to be that you are not assigning the required object to localStorage, but rather the string property, meaning you are overwriting the key new-info with a string. Try saving the entire object instead, like this:

 const info = { name: '', description: '' }; function setName(value) { info.name = value; saveToStorage(); }; function setDescription(value) { info.description = value; saveToStorage(); }; function saveToStorage() { localStorage.setItem('new-info', JSON.stringify(info)); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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