1

I am trying to store an array in localStorage (HTML5) which needs to be a string, but enable direct access to objects I store in the array by defining the index. When I try to JSON.stringify I just get [] which doesn't store the array of objects in localStorage.

var mylist = [];

mylist["mykey1"] = {id: "1", title: "First"};
mylist["mykey2"] = {id: "2", title: "Second"};

localStorage.setItem("mylist", JSON.stringify(mylist));  // stores [] only - uggh!

var mylist2 = JSON.parse(localStorage.getItem("mylist"));

document.write(JSON.stringify(mylist2["mykey1"])); // want it to display:  {"id": "1", "title": "First"}
Mike S.
  • 4,806
  • 1
  • 33
  • 35

3 Answers3

1

I think I solved it just by changing the mylist var from [] array to {} object.

var mylist = {};
Mike S.
  • 4,806
  • 1
  • 33
  • 35
1

You've created an array and you're trying to use it like an associative array or map

What's actually happening is when you type

mylist["mykey1"] = {id: "1", title: "First"}

It's trying to get a list element at index "mykey1", which is being ignored by the JSON parser. This is probably due to the fact that it cannot determine an integer index into your list for mykey1, or it's conversion to a number is too large.

You'll notice that if you do this:

mylist[1] = {id: "1", title: "First"}

Your JSON string will be "[null,{id: "1", title: "First"}]", as you haven't specified a 0th index element, but you have set the 1st index element.

Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • Well, that's not completely true (or I misunderstood). `mylist` will have a property `mykey1` with that value, but it will be ignored by `JSON.stringify`. – Felix Kling Aug 10 '12 at 02:11
0

Because you are using an array as a normal object.

Change var mylist = []; to var mylist = {};, then thing will be work.

Check the demo.

xdazz
  • 158,678
  • 38
  • 247
  • 274