Saving an Array in Local Storage from Javascript

  • Estimated read time: 1 min read
  • Written by Chad Campbell on Feb 15th 2012

With the HTML Local Storage feature, you have a more powerful approach to storing information over the traditional cookie. At first glance, this feature appears to only work with strings. But, you may need to store something more complex. Like a collection, or an array of JSON objects. That was the situation I ran into when I got an education on this feature.

Storing an Array in Local Storage

‚ÄčTo store a collection or array in local storage, you must first convert it to a string. To do that, you can use something like the following:

var myCollection = { "people":[
    {'ID': 1, 'FirstName':'Chad', 'LastName':'Campbell'},
    {'ID': 2, 'FirstName':'John', 'LastName':'Smith'}
localStorage.setItem('collectionKey', JSON.stringify(myCollection));

In the previous snippet, we took a JSON array and we made it into a string. This process of converting it to a string was handled by the ever-popular, ever-useful JSON.stringify function. This native function in modern browsers handles the process of serializing the data. To get an array from local storage and convert it back to JSON is covered here.


comments powered by Disqus

Chad Campbell
Chad Campbell

Chad is an independent software professional. He has been named a Microsoft MVP five times. His books have been translated into multiple languages and distributed worldwide. He holds a computer science degree from Purdue University, where he also studied psychology.

Chad has built sites, apps, frameworks, libraries, and platforms using Java, .NET, and Node. He's ran his own startups and has created software for Fortune 100 companies. In short, Chad knows how to create software. From ideation to delivery. From start-to-finish.

Follow Chad Online