The localStorage
API in browsers only supports adding information in a key:pair
format and the key
and the pair
should be of type string
thus native objects or arrays cannot be stored in the localStorage
.
To save arrays or objects using the localStorage
API in JavaScript, we need to first stringify
the arrays or objects using the JSON.stringify()
method, and when we need to retrieve the value we can use the JSON.parse()
method.
Consider this object,
// an object
const John = {
name: "John Doe",
age: 23,
};
To save this object to the localStorage
First, we need to convert the John
object into a JSON string. For that let's use the JSON.stringify()
method and pass the object as an argument to the method.
It can be done like this,
// an object
const John = {
name: "John Doe",
age: 23,
};
// convert object to JSON string
// using JSON.stringify()
const jsonObj = JSON.stringify(John);
Now let's use the setItem()
method on the localStorage
and pass the key name as the first argument to the method and the jsonObj
as the second argument to the method like this,
// an object
const John = {
name: "John Doe",
age: 23,
};
// convert object to JSON string
// using JSON.stringify()
const jsonObj = JSON.stringify(John);
// save to localStorage
localStorage.setItem("John", jsonObj);
Now to retrieve the value from the localStorage
, we can use the getItem()
method on the localStorage
API and then convert the string to a valid object using the JSON.parse()
method.
It can be done like this,
// an object
const John = {
name: "John Doe",
age: 23,
};
// convert object to JSON string
// using JSON.stringify()
const jsonObj = JSON.stringify(John);
// save to localStorage
localStorage.setItem("John", jsonObj);
// get the string
// from localStorage
const str = localStorage.getItem("John");
// convert string to valid object
const parsedObj = JSON.parse(str);
console.log(parsedObj);
Great! 🌟 We have successfully stored and retrieved from the localStorage
API.
See this example live in JSBin.
The process is the same for arrays too.
See this example using arrays,
// an array
const arr = [1, 2, 3, 4, 5];
// convert array to JSON string
// using JSON.stringify()
const jsonArr = JSON.stringify(arr);
// save to localStorage
localStorage.setItem("array", jsonArr);
// get the string
// from localStorage
const str = localStorage.getItem("array");
// convert string to valid object
const parsedArr = JSON.parse(str);
console.log(parsedArr);
See this example live in JSBin.