Practice Set - localStorage
by jessupjs
HTML
<p>There is one part to this practice problem. This exercise is designed to get you comfortable with using <code>window.localStorage</code>, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage" target="_blank">Storage object</a>, and the utilities of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify" target="_blank">JSON object</a>.</p>
<ol>
<li>On lines 11-12, the <code>personInfo</code> object is being converted into a string using JSON.stringify(), and assigned to localStorage. Your task is to do the opposite: retrieve the string from localStorage (Storage.getItem() may help), and output it to the page using the logMessage() function that's provided.
</li>
<p><b>Output:</b>
</p>
<div id="output"></div>
CSS
#output {
border:1px solid black;
padding: .5em;
}
JavaScript
// Initialize our personInfo Object
var personInfo = {
fname: "Bill",
lname: "Adama",
addr: "Galactica CIC",
email: "N/A",
title: "Admiral",
}
// Write the object to localStorage
var jsonPerson = JSON.stringify(personInfo);
window.localStorage.setItem("person", jsonPerson);
// Insert your code below to read the object back from localStorage,
// convert it back to an object,
// and iterate over its properties, printing the property names and their
// values using the logMessage() function. This last part should be
// identical to code you wrote for the previous pratice set
var personInfo = JSON.parse(jsonPerson);
for (var key in personInfo) {
var display = key + " : " + personInfo[key];
logMessage(display);
}
// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id) {
if (!id) {
id = "output";
}
document.getElementById(id).innerHTML += msg + "<br>";
}