Week 6: Assignment 3

by Larry Adams

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

console.clear();

// 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

// print the person OBJECT to the console
        console.log(personInfo);

// get the person String from Local Storage
        var persistedPerson = localStorage.getItem("person");
        // print the contact to the console
        console.log(persistedPerson);

// convert person String to an object
        var personObject = JSON.parse(persistedPerson);
        // print the object to the console
        console.log(personObject);

// display 
for (var c in personInfo) {
   console.log("The contact's " + c + " is " + personInfo[c] + ".");
}

var personname = 'fname';

logMessage(personInfo.fname); // Bill
logMessage(personInfo.lname); // Adama
logMessage(personInfo.addr); // Galactica CIC
logMessage(personInfo.email); // N/A
logMessage(personInfo.title); // Admiral


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