Jonas
Jonas

Reputation: 2249

JavaScript LocalStorage of Array with String Keys

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

Example:

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:

localStorage.setItem('myStoredArray',JSON.stringify(myArray));
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!

Upvotes: 1

Views: 146

Answers (2)

Aaron
Aaron

Reputation: 24802

As stated by Daniel in the comments, your array isn't just badly persisted, it's badly created.

You can easily see it in your browser's console :

>var myArray = [];
<undefined
>myArray["key1"] = "value1";
<"value1"
>myArray
<[]

As you can see, trying to assign a value to an array through a String key doesn't work.

You can try using ES6 Maps or an object.

Since Daniel already answered with the Object method, here's the Map one :

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("123", "value2");

And the advantage of a Map is a somewhat easier iteration :

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190907

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

Upvotes: 3

Related Questions