1

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!

8
  • 1
    You need to parse it before reading it.. Commented May 2, 2016 at 12:15
  • I missed it in my example. That's not the problem. Otherwise the rest wouldn't have worked Commented May 2, 2016 at 12:17
  • @Rayon Thanks anyways Commented May 2, 2016 at 12:17
  • 1
    there are no associative arrays in javascript. you should use an object. Commented May 2, 2016 at 12:19
  • 1
    You are adding a property to an array object. It's not serialized as JSON. So the parsed/new array doesn't have such property. That's not how JSON works. Commented May 2, 2016 at 12:22

2 Answers 2

3

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I'll accept this as soon as it lets me!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.