Use Object in LocalStorage
<html>
<head>
<title>Use Object in LocalStorage</title>
</head>
<body>
<form>
<input type="button" value="Write Object" onclick="writeObject()">
<input type="button" value="Read Object" onclick="readObject()">
<br>
<div id="result"></div>
</form>
<script type="text/javascript">
function writeObject() {
var product = {
id: 'p01',
name: 'name 1',
price: 20
};
localStorage.setItem('product', JSON.stringify(product));
}
function readObject() {
var product = JSON.parse(localStorage.getItem('product'));
var result = 'Id: ' + product.id;
result += '<br>Name: ' + product.name;
result += '<br>Price: ' + product.price;
document.getElementById('result').innerHTML = result;
}
</script>
</body>
</html>
Run Application
Open site in browser and display as below:
Write Object
Read Object