Posted By

burnandbass on 10/23/14


Tagged

parse json local storage localstorage stringify


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

stepvda


Add/Get objects From/To LocalStorage


 / Published in: JavaScript
 

saveToStorage("objectName", {javascript:"object"});

To get the object use getFromStorage("objectName");

If the object does not exist, the function returns new empty object;

  1. //Save object
  2. function saveToStorage(_name, _obj) {
  3. console.log("saved to storage", _name, _obj);
  4. localStorage.setItem(_name, JSON.stringify(_obj));
  5. }
  6.  
  7. //Get the object, or a new one
  8. function getFromStorage(_name) {
  9. var storageData = localStorage.getItem(_name);
  10. var storageObj = JSON.parse(storageData);
  11.  
  12. if (!storageObj) {
  13. storageObj = {};
  14. saveToStorage(_name, storageObj);
  15. }
  16. return storageObj;
  17. }

Report this snippet  

You need to login to post a comment.