How to save an object in an object object in JavaScript using LocalStorage?

I am new to JS, and before asking, I searched for this question, but still have not found an answer. In LocalStorage, I have only one key defined as follows:

key={
  -prob1: string
  -prob2: Object 
      -prob21:string 
      -prob22:string
}

How can I save to a keygiven object the same structure as prob2, call it obj, is that so? localStorage.setItem('key.prob2', obj);Is it legal?

any ideas? thank

+4
source share
2 answers

You cannot store objects with localStorage- you can only store strings there.

What you can do is convert your object to a string (using JSON.stringify) and then save it.

obj = {
  a: {
    b: 'c'
  }
}

localStorage.setItem('myobj', JSON.stringify(obj));

console.log(localStorage.getItem('myobj'));
console.log(JSON.parse(localStorage.getItem('myobj')));

https://jsfiddle.net/or91wp56/

+4

, localStorage.setItem('key.prob2', obj), [object Object], , , , , . localStorage /, :

class Storage {
   static set(key, value) {
      let serialized = value;
      if (typeof value !== 'string') {
         serialized = JSON.stringify(serialized);
      }
      localStorage.setItem(key, serialized);
   }
   static get(key) {
      try {
         return JSON.parse(localStorage.getItem(key));
      } catch (e) {
         return localStorage.getItem(key);
      }
   }
}

Storage.set('foo', { bar: 'baz' });
console.log(Storage.get('foo').bar);
+1

Source: https://habr.com/ru/post/1683928/


All Articles