localStorage getItem logs[object Object]

zinho picture zinho · May 22, 2014 · Viewed 24.1k times · Source

I am trying to set and get items from local storage but when i log the data i get [object Object]

i am trying to get the view of that object something like this {a : v, b : v }...

here is the code :

var widgets = localStorage.getItem('widgets');
        if (widgets == null) {
         widgets = {
            widget_lot : '',
            widget_td : '',
            widget_cwo : '',
            widget_vehicles : '',
            widget_take : ''
            };  

            widgets.widget_lot = 0;
            widgets.widget_td = 0;
            widgets.widget_cwo = 1;
            widgets.widget_vehicles = 0;
            widgets.widget_take = 0;

            localStorage.setItem('widgets', widgets);
        }

        console.log(widgets); //Logs "[object Object]"

Answer

brainless coder picture brainless coder · May 22, 2014

Local storage only supports string datatype. So you have to

  1. Convert it to String before saving to LocalStorage

    localStorage.setItem('key', JSON.stringify(data));
    
  2. Convert back to JS object, reading from LocalStorage

    data = JSON.parse(localStorage.getItem('key')); //forgot to close
    

In case of your code, it should be -

var widgets = JSON.parse(localStorage.getItem('widgets'));

and

localStorage.setItem('widgets', JSON.stringify(widgets));