Storing Objects in HTML5 localStorage and sessionStorage
Objects are not natively supported within HTML5's localStorage or sessionStorage. Attempting to store an object directly will result in it being serialized to a string.
To circumvent this limitation, consider the following workaround:
Example:
const testObject = { 'one': 1, 'two': 2, 'three': 3 }; // Stringify and store localStorage.setItem('testObject', JSON.stringify(testObject)); // Retrieve and parse const retrievedObject = JSON.parse(localStorage.getItem('testObject')); console.log('Retrieved object:', retrievedObject);
This technique allows you to store and retrieve JavaScript objects in localStorage and sessionStorage despite their inherent string-based storage nature.
The above is the detailed content of How Can I Store and Retrieve JavaScript Objects in HTML5 localStorage and sessionStorage?. For more information, please follow other related articles on the PHP Chinese website!