4

I am new at JS and before asking I searched about this question but still did not find an answer. In the LocalStorage I have only one key defined as follows:

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

How can I store in key a given object of the same structure as prob2 let's call it obj , is it like this ? localStorage.setItem('key.prob2', obj); is this legal?

any ideas?thank you

2 Answers 2

4

You can't store Objects using localStorage - you can only store there strings.

What you can do is convert your object to 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/

Sign up to request clarification or add additional context in comments.

4 Comments

thank you for replying , but I want to store obj in one property in myobj and not in myobj itself
You can always read that obj, insert new object in one of the properties, and save it back to the localStorage
I thought it was easy, I've been trying since hours, nothing is solving it ,how do you do that?
never mind , I'm the one who did it not quiet correct.. Thank you!
1

All you'd be storing with localStorage.setItem('key.prob2', obj) is [object Object] since it can only store strings, which probably isn't what you are looking for. I usually use a small wrapper class around localStorage to auto-serialize/deserialize, something like:

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.