Home > Web Front-end > JS Tutorial > How Can I Store and Retrieve JavaScript Objects in HTML5 localStorage and sessionStorage?

How Can I Store and Retrieve JavaScript Objects in HTML5 localStorage and sessionStorage?

Susan Sarandon
Release: 2024-12-25 18:47:10
Original
893 people have browsed it

How Can I Store and Retrieve JavaScript Objects in HTML5 localStorage and sessionStorage?

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:

  1. Stringify the Object: Before storing the object, convert it into a JSON string using JSON.stringify.
  2. Store the String: Assign the JSON string to a key in localStorage or sessionStorage using setItem('key', JSON_string).
  3. Retrieve the String: When fetching the object, obtain the JSON string using getItem('key').
  4. Parse the String: Convert the retrieved string back into an object using JSON.parse.

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template