By David


2010-07-28 21:14:27 8 Comments

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?

6 comments

@Dagg Nabbit 2010-07-28 21:23:36

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

@Saif Bechan 2011-11-22 08:44:30

JSON is not supported in IE7 and earlier.

@tungd 2012-01-10 04:40:13

@SaifBechan Don't worry about IE 6/7, we are talking about localStorage

@Howdy_McGee 2013-02-26 06:08:41

Can somebody explain why you have to do this and what is going on please?

@James Coyle 2013-03-03 00:10:41

@Howdy_McGee As localStorage only supports strings, arrays must be converted to a string format. The best way to do this is to convert it into a JSON array as it is easy to convert between the two states (JSON is just a long piece of string data). You may want to read up on JSON if that is what you don't understand. :)

@Howdy_McGee 2013-03-03 20:15:17

Didn't realize localStorage only holds string. That's fairly limiting but I suppose anything more complicated would also need to be more secure and probably last long. @jimjimmy1995 Thanks!

@Jonathan Tonge 2013-03-15 19:21:57

I would test whether localStorage['names'] returns a value before parsing it or an error will be thrown.

@Dagg Nabbit 2013-04-12 00:17:35

@JonathanTonge, you could do something like JSON.parse(localStorage["names"] || null) if you wanted.

@Francisc 2014-05-09 19:02:41

how can I store more then one name?

@David Wihl 2016-03-07 14:56:29

If you compress the resulting string, up to 4x times as much data can be stored. See jsfiddle.net/davidwihl/n12rogcx (uses the LZ JavaScript library: pieroxy.net/blog/pages/lz-string/index.html)

@Michaël van de Weerd 2016-03-16 08:53:47

@SaifBechan if(typeof JSON == "undefined") { alert("Upgrade your browser."); }

@int soumen 2017-11-18 07:25:06

I have a situation. Array['t1'] = 'Hello'. I am unable to store Array to localStorage. My case JSON.stringify(Array) is returning []. When it can be happened?

@jayeff 2010-08-02 21:33:38

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

@Phil 2013-06-19 14:35:29

Can you show us a better alternative?

@ChiefTwoPencils 2014-07-12 09:20:18

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

@J0HN 2014-07-12 10:37:19

@ChiefTwoPencils have you read comments before flagging?

@ChiefTwoPencils 2014-07-12 15:18:38

@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?

@jayeff 2014-07-13 11:13:00

@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"?

@Squ1rr3lz 2017-10-31 21:47:16

@jayeff How do I loop through this to check corresponding attributes (i.e., firstName = John, lastName = doe, dob = 1/1/1989)? I need to do a check (if these attributes match whats in localStorage then call a certain function.)

@Klederson Bueno 2012-10-16 18:44:55

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

@twobob 2016-02-24 23:50:45

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.

@Lassi Kinnunen 2012-04-26 10:04:28

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

@Sebastian 2012-04-11 15:40:44

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.

Source: http://www.acetous.de/p/152

@Dvid Silva 2013-11-16 23:29:27

if you needed all of them how would you retrieve them?

@Sebastian 2013-12-05 11:55:46

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

@Parag Gangil 2014-06-11 09:06:24

@Sebastian using localStorage.length could be wrong in some cases if the website is also localStorage to store something.

@Sebastian 2014-10-06 21:15:35

You may prefix your module specific values and delete everything with that prefix while iterating all elements of localStorage.

@zevero 2016-09-28 10:26:24

I used the same approch in my solution, which provides a minimalistic interface to how localStorage should work :) github.com/zevero/simpleWebstorage

@Venkat Raj 2018-04-11 09:36:44

Can I store browser tab object in local storage by implementing above concept?

@Znarkus 2012-01-09 21:53:34

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

@Camilo Martin 2012-02-23 15:05:04

Kills the performance gain of not JSONifying.

@Znarkus 2012-02-23 19:15:01

@CamiloMartin Yeah that's probably true.. :)

@PiTheNumber 2013-08-26 18:26:17

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.

@Znarkus 2013-08-26 19:20:25

@PiTheNumber If names_keys contains an array of indices, isn't that a chicken/egg situation?

@PiTheNumber 2013-08-27 07:11:13

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

@Alix Axel 2014-04-16 15:59:28

@PiTheNumber What is hugh?

@PiTheNumber 2014-04-22 16:03:47

@AlixAxel I don't have an exact number for you but if things are slowing down because of reindexing or you just don't like to rebuild the index you might want to consider storing the keys instead. Or the other way around: If you store 10'000 integer values your index in names_keys would be larger than you actually data.

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] Storing Objects in HTML5 localStorage

48 Answered Questions

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6249452 View
  • 7806 Score
  • 93 Answer
  • Tags:   javascript arrays

54 Answered Questions

[SOLVED] Remove duplicate values from JS array

30 Answered Questions

[SOLVED] Open a URL in a new tab (and not a new window)

  • 2011-02-05 15:52:13
  • Mark
  • 2450095 View
  • 1983 Score
  • 30 Answer
  • Tags:   javascript

37 Answered Questions

[SOLVED] For-each over an array in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

4 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

30 Answered Questions

[SOLVED] How to append something to an array?

Sponsored Content