837

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?

2
  • I have posted up a complete solution for maintaining arrays in localStorage or sessionStorage at the thread this was closed as a duplicate of, because nether thread really answers the question originally posed by Dave: stackoverflow.com/a/23516713/2208713. Hope it helps some people. May 7, 2014 at 11:37
  • Easy way to handle that kind of condition you can use opendb library very use full to deal with array, object. You can follow this link github.com/pankajbisht/openDB Jan 24, 2018 at 10:58

6 Answers 6

1578

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"));

You can also use direct access to set/get item:

localStorage.names = JSON.stringify(names);
var storedNames = JSON.parse(localStorage.names);
9
  • 6
    JSON is not supported in IE7 and earlier. Nov 22, 2011 at 8:44
  • 529
    @SaifBechan Don't worry about IE 6/7, we are talking about localStorage
    – tungd
    Jan 10, 2012 at 4:40
  • 1
    I would test whether localStorage['names'] returns a value before parsing it or an error will be thrown. Mar 15, 2013 at 19:21
  • 7
    @JonathanTonge, you could do something like JSON.parse(localStorage["names"] || null) if you wanted. Apr 12, 2013 at 0:17
  • 3
    @SaifBechan if(typeof JSON == "undefined") { alert("Upgrade your browser."); } Mar 16, 2016 at 8:53
145

The localStorage and sessionStorage can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Use localStorage.setObj(key, value) to save an array or object and localStorage.getObj(key) to retrieve it. The same methods work with the sessionStorage object.

If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.

5
  • 1
    if you needed all of them how would you retrieve them?
    – Dvid Silva
    Nov 16, 2013 at 23:29
  • 1
    The storage objects provide the property "length" to determine the count of saved objects and the method "key(int index)" to get the current key. So you can try: for (var i = 0; i < localStorage.length; i++) console.log( localStorage.key(i) +" has value " + localStorage[localStorage.key(i)] )
    – Sebastian
    Dec 5, 2013 at 11:55
  • 1
    @Sebastian using localStorage.length could be wrong in some cases if the website is also localStorage to store something.
    – PG1
    Jun 11, 2014 at 9:06
  • You may prefix your module specific values and delete everything with that prefix while iterating all elements of localStorage.
    – Sebastian
    Oct 6, 2014 at 21:15
  • 1
    I used the same approch in my solution, which provides a minimalistic interface to how localStorage should work :) github.com/zevero/simpleWebstorage
    – zevero
    Sep 28, 2016 at 10:26
19

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).

5
  • Can you show us a better alternative?
    – Phil
    Jun 19, 2013 at 14:35
  • 13
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. Jul 12, 2014 at 9:20
  • @ChiefTwoPencils have you read comments before flagging?
    – J0HN
    Jul 12, 2014 at 10:37
  • 2
    @J0HN: yes I did. Since when is a members reputation good reason to break the rules? In fact, doesn't the auto-messaging on recommended deletions specifically mention not posting commentary as answers and suggests the poster wait until they have enough reputation to comment and up-vote until then? Poster says it's not an answer; what more evidence needs to exist? Jul 12, 2014 at 15:18
  • 2
    @ChiefTwoPencils: Some historical context: When I posted this comment the accepted answer proposed doing a join and split with "|||" by Ian (Note: this answer no longer exists). Because I considered this answer actually harmful I posted my answer. Today my non-answer is no longer necessary (the correct answer is accepted and has a healthy dose of upvotes). I'm not too familiar with the guidelines: Is it ok/recommended to delete my "answer"?
    – jayeff
    Jul 13, 2014 at 11:13
9

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');
1
  • 3
    This is the sort of thing I was looking for, except it would walk the keys of the provided object and save the (single) linked value in each. Much obliged for the inspire.
    – twobob
    Feb 24, 2016 at 23:50
4

The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.

at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).

2

Another solution would be to write a wrapper that store the array like this:

localStorage.setItem('names_length', names.length);
localStorage.setItem('names_0', names[0]);
localStorage.setItem('names_1', names[1]);
localStorage.setItem('names_' + n, names[n]);

Removes the overhead of converting to JSON, but would be annoying if you need to remove elements, as you would have to re-index the array :)

6
  • 1
    Kills the performance gain of not JSONifying. Feb 23, 2012 at 15:05
  • 1
    Instead of names_length use names_keys and you don't need to re-index! This would also allow you to use string keys. Of course this makes only sense if the array elements are kind of hugh. Aug 26, 2013 at 18:26
  • @PiTheNumber If names_keys contains an array of indices, isn't that a chicken/egg situation? Aug 26, 2013 at 19:20
  • @Znarkus As I said, this makes only sense for hugh array elements. If you have for example 100KB per element it would be better to use a small entry with keys. Aug 27, 2013 at 7:11
  • @PiTheNumber What is hugh?
    – Alix Axel
    Apr 16, 2014 at 15:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.