JavaScript Object Storage in HTML5 Session and Local Storage

JavaScript Object Storage in HTML5 Session and Local Storage
JavaScript Object Storage in HTML5 Session and Local Storage

Working with Objects in Web Storage

While using HTML5 localStorage or sessionStorage, developers frequently find problems while attempting to store JavaScript objects. Unlike primitive data types and arrays, objects appear to be converted to strings, which can cause confusion and unexpected outcomes.

Understanding how to properly save and retrieve objects via Web Storage is critical for many web applications. This tutorial will explain why objects are changed to strings and suggest a simple solution to ensure that your objects are correctly stored and retrieved.

Command Description
JSON.stringify() Converts a JavaScript object or value to a JSON string, which can then be stored in local or session storage.
localStorage.setItem() Stores a key-value pair in the localStorage object, allowing data to be saved between browser sessions.
localStorage.getItem() Returns the value associated with a particular key from localStorage.
JSON.parse() Parses a JSON string and returns a JavaScript object, allowing for the retrieval of sophisticated data structures.
sessionStorage.setItem() The sessionStorage object stores a key-value pair, allowing data to persist for the life of the page's session.
sessionStorage.getItem() Returns the value associated with a particular key from sessionStorage.

Storing and retrieving objects in Web Storage

In JavaScript, localStorage and sessionStorage are web storage objects that enable you to save key-value pairs in the browser. However, these storage options only handle strings, so attempting to store a JavaScript object directly will result in the object being transformed to a string representation such as [object Object]. To successfully save items, transform them to a JSON string with JSON.stringify(). This method converts a JavaScript object into a JSON string, which can be stored in localStorage or sessionStorage.

To get the stored object, turn the JSON string back into a JavaScript object with JSON.parse(). This method accepts a JSON string and returns its matching JavaScript object. The scripts in the preceding examples demonstrate this technique. First, an object is generated and transformed to a JSON string with JSON.stringify() before being put in localStorage with localStorage.setItem(). The object is retrieved by fetching the JSON string from localStorage with localStorage.getItem() and parsing it into a JavaScript object with JSON.parse().

Storing and retrieving JavaScript objects in localStorage

Using JavaScript and JSON for local storage.

// Create an object
var testObject = {'one': 1, 'two': 2, 'three': 3};

// Convert the object to a JSON string and store it in localStorage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the JSON string from localStorage and convert it back to an object
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));

// Verify the type and value of the retrieved object
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ', retrievedObject);

// Output should be:
// typeof retrievedObject: object
// Value of retrievedObject: { one: 1, two: 2, three: 3 }

Storing and retrieving JavaScript objects in sessionStorage.

Using JavaScript and JSON for session storage.

// Create an object
var testObject = {'one': 1, 'two': 2, 'three': 3};

// Convert the object to a JSON string and store it in sessionStorage
sessionStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the JSON string from sessionStorage and convert it back to an object
var retrievedObject = JSON.parse(sessionStorage.getItem('testObject'));

// Verify the type and value of the retrieved object
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ', retrievedObject);

// Output should be:
// typeof retrievedObject: object
// Value of retrievedObject: { one: 1, two: 2, three: 3 }

Advanced Techniques for Web Storage

Using HTML5 localStorage and sessionStorage, developers frequently need to store complicated data beyond just strings. While JSON serialization and deserialization are useful for basic objects, more complex circumstances may necessitate extra considerations. For example, if you're dealing with deeply nested objects or objects that have methods, you'll need a more advanced technique. To manage circular references and complex object structures, one typical approach is to utilize a library like Flatted or circular-json.

These libraries improve the standard JSON.stringify() and JSON.parse() techniques by supporting serialization and deserialization of objects with circular references. This allows for a more reliable solution for storing objects in web storage. Data compression is also an important concern. Libraries like LZ-String can compress huge items before storing them in localStorage or sessionStorage, saving space. This is especially beneficial for applications that need to store large amounts of client-side data.

Common Questions About Storing Objects in Web Storage

  1. Can I store functions as localStorage or sessionStorage?
  2. No, functionalities cannot be saved directly to online storage. The function code can be stored as a string and recreated with eval(), although this is not recommended due to security risks.
  3. How do I deal with circular references in objects?
  4. Use libraries like Flatted or circular-json that handle circular references in JavaScript objects.
  5. What is the storage limit for localStorage.
  6. The storage limit for localStorage is normally approximately 5MB, although it can vary depending on browser.
  7. Can I compress data prior to storing it?
  8. Yes, you may compress your data using libraries like LZ-String before saving it in localStorage or sessionStorage.
  9. How can I save an array of objects?
  10. Convert the array to a JSON string with JSON.stringify() before saving it in localStorage or sessionStorage.
  11. Is it secure to keep sensitive data in localStorage?
  12. No, storing sensitive data in localStorage is not secure because it is accessible via JavaScript and can be compromised if the site is attacked.
  13. Can I use 0 across domains?
  14. No, localStorage is limited to the same origin, which means it cannot be accessed from various domains.
  15. What happens if a person clears their browser data?
  16. Clearing the user's browser data will delete all data stored in localStorage and sessionStorage.

Final thoughts on Managing Object Storage

To save and retrieve objects in HTML5 web storage, transform them to JSON strings using JSON.stringify() and then parse them back with JSON.parse(). This method ensures that the data is preserved and useful over multiple browser sessions. Understanding and implementing these strategies enables developers to use localStorage and sessionStorage for more complicated data management activities, improving the functionality and performance of their web apps.