Q:

How to Store JavaScript Objects in HTML5 localStorage

0

How to Store JavaScript Objects in HTML5 localStorage

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JSON.stringify() Method

By default, the localStorage or sessionStorage only allows you to store string key/value pairs. But you can also store the JavaScript objects in web storage with a little trick.

To store objects first stringify it using the JSON.stringify() method, and later parse it with the JSON.parse() when you need retrieve it, as shown in the following example:

<script>
var personObject = { name: "Peter", age: 18, married: false };
    
// Convert the person object into JSON string and save it into storage
localStorage.setItem("personObject", JSON.stringify(personObject));
    
// Retrieve the JSON string
var jsonString = localStorage.getItem("personObject");
    
// Parse the JSON string back to JS object
var retrievedObject = JSON.parse(jsonString);
console.log(retrievedObject);
    
// Accessing individual values
console.log(retrievedObject.name); // Prints: Peter
console.log(retrievedObject.age); // Prints: 18
console.log(retrievedObject.married); // Prints: false
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get Portion of URL Path in JavaScript... >>
<< How to Call Multiple JavaScript Functions in onCli...