Saving an Array of Favorite Objects using localStorage in JavaScript

Greg Wright
3 min readApr 2, 2021

I was once challenged to save some data so that it would persist when the user refreshed the page, in this case, the data was an array of favorite objects that would need to persist. After doing some digging I quickly came across localStorage in the MDN Web Docs. After looking over its documentation I quickly came to the conclusion that localStorage was exactly what I needed. Here is a simplified rundown of how to get local storage to persist an array of objects.

First, we start with our initial array of objects. For this example, we’ll make an array of fruit objects.

Then we create an empty array that will house our favorite fruit objects.

In order to use local storage, you must use the localStorage property combined with methods of the storage interface. For localStorage there are 4 methods we can use:

To add data to local storage we use:

To retrieve data from local storage we use:

To remove particular data from local storage we use:

And to completely clear everything from local storage we use:

Let’s put some of these into practice on our favoiteFruites array.

First, we’ll push one of the fruit objects from our array of fruit objects into our favorite fruits array and then set our favorite fruit array into local storage. Let’s give it a shot.

It looks like we were able to add a fruit object of orange to our favoriteFruit array, but when we console.log the local storage we are seeing [object Object] instead of the object itself. The problem here is that localStorage only accepts strings for storage. In order to fix this problem we need to convert our object into a string, also known as serializing, and the way we’ll serialize our object is with JSON.stringify().

Let's try this again.

As you can see we now have our object stored as a string in local storage.

In order to retrieve our item from local storage, we must first convert it from a string back to an object. To do this we use localStorage.getItem() combined with JSON.parse and save it to a new variable.

Now we can use our object as we normally would, but pulled from local storage which will persist across page refresh.

Thanks for reading.

Resources:

--

--