user8244016
user8244016

Reputation: 1019

How to store an object in an object of objects in JavaScript using LocalStorage?

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

Upvotes: 4

Views: 2324

Answers (2)

Rob M.
Rob M.

Reputation: 36511

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

Upvotes: 1

Dekel
Dekel

Reputation: 62556

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/

Upvotes: 4

Related Questions