How to store objects with HTML5 localStorage

#javascript #html5

Last updated on May 31, 2021 by Suraj Sharma



In this tutorial, you will learn to store JavaScript objects and arrays in the Storage object with HTML5 window.localStorage.

window.localStorage property stores the data in the Web API Storage object.

localStorage allows you to access the Storage object from the global window object, for example


 console.log(window.localStorage);
// Storage{length: 0}

// store a new key-value pair with localStorage

localStorage.setItem("animal", "cat")

localStorage.getItem("animal) // "cat"

The keys and the values stored with localStorage are always UTF-16 strings.

That's why, when we store an object value with localStorage, It gets converted into [object Object] string.


// store objects with localStorage

localStorage.setItem("emptyObject", {});

// getting the object with localStorage,
//returns a string instead of the emptyObject

localStorage.getItem("emptyObject); // "[object Object]"


How to store objects with localStorage


To store objects or arrays, you have to

  1. use JSON.stringify() method to convert the objects or the arrays to JSON strings and then,

  2. store the strings to the Storage object using localStorage.setItem() method


const obj = {
  id: 1,
  name: "Suraj",
  city: "Bangalore"
};

const jsonString = JSON.stringify(obj);

localStorage.setItem("user", jsonString);

localStorage.getItem("user");
// "{\"id\":1,\"name\":\"Suraj\",\"city\":\"Bangalore\"}"

To get back the original object with localStorage.getItem(), use the JSON.parse() method to parse the JSON string, constructing the original JavaScript object.


const originalObj = JSON.parse(localStorage.getItem("user"));

console.log(originalObj);
// {id: 1, name: "Suraj", city: "Bangalore"}


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.