Question

I'm trying to print a nice overview of all localstorage items on my html page. I made the following loop to achieve that:

for (var i = 0; i < localStorage.length; i++){
    var entry = localStorage.getItem(localStorage.key(i));
    $('body').append('<article rel="'+entry[0]['key']+'"><h2>'+entry[0]['title']+'</h2><img class="entry_img" src="'+entry[0]['image']+'"><p><span class="actions"><img class="delete" src="img/deleteicon.png" /></span>'+entry[0]['content']+'<span class="time">Toegevoegd op:'+entry.[0]['date']+'</span>'+entry.[0]['location']+'</p></article>');
}

Each item in localstorage is a nice array with information in it. It thought this code should print the values. But it gives me a bunch of undefined's. How can I correctly access the values?

An example of an entry when logged:

1396267647 => {"title":"Entry 1","image":"http://www.hdwallpapersinn.com/wp-content/uploads/2013/03/landscape_10.jpg","content":"Entry 1","date":"31-03-14","location":"Tilburg","key":1396267647}
Était-ce utile?

La solution

localStorage is a bunch of string key/value pairs, so entry will always be a string.

Therefore, you probably have something like:

var entry = localStorage.getItem(localStorage.key(i)); // Returns "example"
entry[0] // Returns "e"
entry[0]['key'] // Returns undefined

If you need to store objects in local storage, you need to stringify them first using something like JSON.stringify.

From your edit: Looks like you have a JSON string already, so all you need to do is parse it:

for (var i = 0; i < localStorage.length; i++){
    var entry = JSON.parse(localStorage.getItem(localStorage.key(i))); // Parse the string value
    $('body').append('<article rel="'+entry[0]['key']+'"><h2>'+entry[0]['title']+'</h2><img class="entry_img" src="'+entry[0]['image']+'"><p><span class="actions"><img class="delete" src="img/deleteicon.png" /></span>'+entry[0]['content']+'<span class="time">Toegevoegd op:'+entry.[0]['date']+'</span>'+entry.[0]['location']+'</p></article>');
}

Autres conseils

Well, you have syntax error in your code, look at: entry.[0]['date'], it should be entry[0]['date'] (without the dot).

And the same error is for entry.[0]['location'], remove the dot.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top