LocalStorage getItem and Loop Values

Home / javascript / LocalStorage getItem and Loop Values

Question:
I am storing some values into local storage using the following line of code;
localStorage.setItem(event.lastEventId, JSON.stringify(data));

Looking at the browser console, the storage looks like this;

I want to loop through the localstorage and display the values.

The loop I have so far is;
for (var i = 0; i < localStorage.length; i++) { $("#result").prepend("New transaction " + localStorage.getItem(localStorage.key(i)) + "
");
}

The #result displays the following;

New transaction {"TimeStamp":"2017-08-18 16:34:15","Direction":"Out","CardNo":"40160433","SerialNo":20559458}

New transaction {"TimeStamp":"2017-08-18 16:34:55","Direction":"In","CardNo":"40160432","SerialNo":20559459}

I want to display the values only, not associated keys. For example;

New transaction 2017-08-18 16:34:15, Out, 40160433, 20559458

New transaction 2017-08-18 16:34:55, In, 40160432, 20559459

What do I need to change in order to achieve this?

Any help is appreciated.


Answer:
getItem() returns you a string. So in order to achieve what you want, you need to parse the returned string in JSON and extract the values. Something like this:for (var i = 0; i < localStorage.length; i++) { let data = JSON.parse(localStorage.getItem(localStorage.key(i))); $("#result").prepend("New transaction " + data.TimeStamp + ", " + data. Out + ", " + data. CardNo + ", " + data. SerialNo + "
");
}
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *