How do I store an array in localStorage? [duplicate]

  1. Home
  2. javascript
  3. How do I store an array in localStorage? [duplicate]

This question already has an answer here:

If I didn’t need localStorage, my code would look like this:

var names=new Array(); 
names[0]=prompt("New member name?");

This works. However, I need to store this variable in localStorage and it’s proving quite stubborn. I’ve tried:

var localStorage[names] = new Array();
localStorage.names[0] = prompt("New member name?");

Where am I going wrong?

First answer

localStorage only supports strings. Use JSON.stringify() and JSON.parse().

var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));

//...
var storedNames = JSON.parse(localStorage.getItem("names"));

Second answer

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars).

Third answer

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
Reprint:https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage
Spread the love

Related articles

Comments are closed.