Add/Get objects From/To LocalStorage


/ Published in: JavaScript
Save to your folder(s)

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

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

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.