0

Having a list as so:

 var names_Array = [];

 var names_List = new WinJS.Binding.List(names_Array);

I push into the list the following:

names_List.push({ name: "Joe Dowling", image: "image/Joe Dowling.png", ClientID: "1234" });
names_List.push({ name: "Esteban Flamenco ", image: "image/Esteban Flamenco.png", ClientID: "6666" });

I then set the list in local storage, as such:

window.localStorage.setItem('names_List', names_List);

Finally I get the item as such:

  var test = window.localStorage.getItem('names_List');
  console.log(test);

I want to be able to print elements of the list in the console. Can anyone guide me on this. I've tried using the names_List.getAt(index) method but to no avail.

user2363025
  • 6,365
  • 19
  • 48
  • 89
  • 1
    I assume you get something like "[object Object]" printed? see http://stackoverflow.com/questions/3357553/how-to-store-an-array-in-localstorage – Damyan Petev Jun 11 '13 at 14:19

1 Answers1

3

You will almost certainly get a bit of a mess here, because localStorage will only store strings. Objects of any other type will be converted to a string. So you'll probably get something like [object Object],[object Object],[object Object],[object Object], the result of an array of objects being converted to a string.

The best way around this is to use JSON.

window.localStorage.setItem('names_List', JSON.stringify(names_List));
var test = JSON.parse(window.localStorage.getItem('names_List'));

This converts objects to strings in a more meaningful way, so you will keep your structure.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Having tried your code, I get this error: 'Circular reference in value argument not supported'. and I'm told it's in relation to: window.localStorage.setItem('names_List', JSON.stringify(names_List)); – user2363025 Jun 11 '13 at 14:33
  • This means your list contains a reference to itself or an object with a reference to itself (a DOM node?) and cannot be turned into JSON. Unless you eliminate the self-reference, you will never be able to pull this off. – Nathan Bubna Jun 11 '13 at 15:01
  • @ Nathan Bubna I don't understand how my list contains a reference to itself. Could you explain this at all? – user2363025 Jun 11 '13 at 15:42
  • @user2363025 An object can contain a reference to itself. For instance, `var object = {}; object.property = object;` It is impossible to serialise that relationship in JSON, so it causes an error. Clearly you have something similar somewhere in your data. Without seeing the data, it is impossible to say precisely what the problem is. – lonesomeday Jun 11 '13 at 16:45