Save array / object to localStorage in JavaScript with sample codes

How to save array or object to localStorage in JavaScript.

It will take a little trickery.

This article explains how to do this with sample code.

localStorage not store array / object

First of all, localStorage doesn’t store array / object.

For example, forcibly write an array to localStorage.

Bad sample code :

/// Try storing array to localStorage
localStorage.setItem('colors', [
    'red', 'green', 'blue'
])

/// Retrieve stored value
localStorage.getItem('colors')
  /// => 'red,green,blue'

Actual localStorage contents :

Array can be accepted but stored as strings.

Suppose you then store the object in localStorage in the same way. If you do so, it will be converted into a string and recorded as ‘[object Object]’, a meaningless value!

How to save array to localStorage

Use the following trick.

  • When saving : convert to JSON string
  • When restoring : parse as JSON

Specifically, add an extension methods for saving array to Storage.

Sample code to extend Storage :

Storage.prototype.getArray = function(key){
  const arr = JSON.parse(
    localStorage.getItem(key) || '[]'
  );
  return arr;
};

Storage.prototype.setArray = function(key, arr){
  localStorage.setItem(key, JSON.stringify(arr))
};

Sample code to save / get array to / from localStorage :

/// Try storing array to localStorage 
localStorage.setArray('colors', [
    'red', 'green', 'blue' 
]) 

/// Retrieve stored array 
localStorage.getArray('colors') 
  /// => ['red', 'green', 'blue']

Of course, arrays with hierarchical structures can also be stored.

How to save object to localStorage

Same as for array.

Add an extension methods for saving Object to Storage.

Sample code to extend Storage :

Storage.prototype.getObject = function(key){
  const obj = JSON.parse(
    localStorage.getItem(key) || '{}'
  );
  return obj;
};

Storage.prototype.setObject = function(key, obj){
  localStorage.setItem(key, JSON.stringify(obj))
};

Sample code to save / get object to / from localStorage :

localStorage.setObject('user', {
  name: 'Pisuke',
  email: 'hoge@hoge.com'
})

localStorage.getObject('user')
  /// => {name: 'Pisuke', email: 'hoge@hoge.com'}

Objects can be directly saved and retrieved.

Leave a Reply