Practice Set - localStorage

by Angeli Schwartz

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:3px solid grey;
    padding: .5em;
    font-weight: bold;
    color: blue;
}

JavaScript

// Initialize our personInfo Object
var personInfo = {
    fname: "Bill",
    lname: "Adams",
    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

// utilized "JSON.parse" & "localstorage.getItem"
// to correctly convert back to an object plus 
// I assigned it to a variable
var getPerson = JSON.parse(window.localStorage.getItem("person"));

// repeated each item in the object
// and write to the page each property and value
for (var key in getPerson){
	logMessage(key + ": " + getPerson[key]);
}


// 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>";
    }