Use Object List in LocalStorage
<html>
<head>
<title>Use Object List in LocalStorage</title>
</head>
<body>
<form>
<input type="button" value="Write Object List" onclick="writeObjectList()">
<input type="button" value="Read Object List" onclick="readObjectList()">
<br>
<div id="result"></div>
</form>
<script type="text/javascript">
function writeObjectList() {
var products = [
{
id: 'p01',
name: 'name 1',
price: 20
},
{
id: 'p02',
name: 'name 2',
price: 21
},
{
id: 'p03',
name: 'name 3',
price: 22
}
];
localStorage.setItem('products', JSON.stringify(products));
}
function readObjectList() {
var products = JSON.parse(localStorage.getItem('products'));
var result = '';
for(var i = 0; i < products.length; i++) {
result += '<br>Id: ' + products[i].id;
result += '<br>Name: ' + products[i].name;
result += '<br>Price: ' + products[i].price;
result += '<br>========================';
}
document.getElementById('result').innerHTML = result;
}
</script>
</body>
</html>
Run Application
Open site in browser and display as below:
Write Object List
Read Object List