How to store objects in HTML5 localStorage

Last updated on Sep 10, 2022 by Suraj Sharma



In this tutorial, you will learn to store JavaScript objects and arrays in the Storage object in 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 in localStorage

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

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

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

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


// store objects in localStorage

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

// getting the object from the localStorage,
//returns a string instead of the empty object

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


How to store objects in 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 from the localStorage.getItem(), use the JSON.parse() method to parse the JSON string to 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 the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.