Here is my HTML code, Here i am storing json Array in localstorage. I want to iterate json later anytime but its showing it undefined. How can i iterate over stored json Array using js ?
<!DOCTYPE html>
<html>
<head>
<script>
var ob=[
{
"id":1,
"name":"one"
},
{
"id":2,
"name":"two"
}
];
function clickCounter() {alert("dsdsd");
if(typeof(Storage) !== "undefined") {
if (sessionStorage.ob) {
sessionStorage.ob = ob;
} else {
sessionStorage.ob = undefined;
}
alert(sessionStorage.ob[0].id);
for (var i in sessionStorage.ob)
{
alert(sessionStorage.ob[i].id);
}
} else {
}
}
</script>
</head>
<body>
<button onclick="clickCounter()" type="button">Click me!</button>
</body>
</html>
localStorage
, like cookies, is for storing strings. If you attempt to store a complex object in storage it will first be cast to its string representation.
Therefore, you need to stringify when saving it and parse it back into a complex object when attempting to iterate over it later.
Save:
var obj = {foo: 'bar'};
localStorage.setItem('obj', JSON.stringify(obj)); //<-- saved as JSON string
Read later:
var obj = JSON.parse(localStorage.getItem('obj'));
for (var i in obj) {
alert(i+' = '+obj[i]); //<-- "foo = bar"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With