Jonas Schafft Jonas Schafft - 10 months ago 26
Javascript Question

JavaScript LocalStorage of Array with String Keys

If i save my array in the localStorage the values saved with String keys are getting lost.


var myArray = [];

myArray["key1"] = "value1";
myArray[123] = "value2";

Everything works and the output of the following works:

myArray["key1"] => value1
myArray[123] => value2

Now if i store the array with something like:

var myArray = JSON.parse(localStorage.getItem('myStoredArray'));

The output is missing the value assigned with a String Key:

myArray["key1"] => undefined
myArray[123] => value2

Am i doing something wrong ,should it work or is there another way to save it that i have my values assigned with String keys?

Thanks in advance!


There is no associative arrays in JavaScript. You should be using an object which will convert all keys to strings.

var myObj = {}; // <<< change here

myObj["key1"] = "value1";
myObj[123] = "value2";