JavaScript – Save Objects in HTML5 Local Storage

This post shows you how to save/store a JavaScript object in HTML5 Local Storage. To do this, we need to convert the object to a JSON string by using JSON.stringify method.

 

Here is the code example:

/// 1. Saving data to localStorage

// user object
var user = {
    name: 'Alex',
    age: 25,
    gender: 'male'
};

// convert the object to JSON string
var userJsonString = JSON.stringify(user);

// save it to localStorage
localStorage.setItem('user', userJsonString);


/// 2. Reading data from localStorage

// get saved data from localStorage
var savedUserJsonString = localStorage['user'];

// convert it to JavaScript object
var savedUserObject = JSON.parse(savedUserJsonString);

In the above code, we use JSON.stringify method to convert the object to JSON string before saving it to localStorage. And then use JSON.parse method to convert the saved data back to JavaScript object when getting data from localStorage.

 

Learn more about How to Store Data in HTML5 Local Storage.

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x