Unit 2B

Updated version

by Larry Adams

JavaScript

// Array to hold Contact Objects
contacts = [];

function Contact(fName, lName, phone) {
    this.fName = fName;
    this.lName = lName;
    this.phone = phone;
}

// add contacts to the array
contacts.push(new Contact("John Harvard", 1233242121));
contacts.push(new Contact("Janet Smith", 4234521216));

// print the contacts to the console
console.log('There are ' + contacts.length + ' contacts in the contacts Array:');
console.log(contacts);
console.log(' ');

// convert contact OBJECT to a String
var jsonContact = JSON.stringify(contacts);
console.log('JSON.stringify(contacts):');
console.log(jsonContact);
console.log(' ');

// clear out the existing contacts from the Array
contacts = [];
console.log('There are ' + contacts.length + ' contacts in the contacts Array:');
console.log(contacts);
console.log(' ');

// store the string in local storage
window.localStorage.setItem("contacts", jsonContact);

// check for contacts in local storage
var persistedContacts = window.localStorage.getItem('contacts');
if (persistedContacts != undefined) {
    persistedContacts = JSON.parse(persistedContacts);
    console.log('JSON.parse(persistedContacts):');
    console.log(persistedContacts);
    console.log(' ');

    // load contacts from local storage into Array (as objects)
    persistedContacts.forEach(function(c) {
        contacts.push(new Contact(c.contactName, c.contactTitle, c.contactID));

        console.log('Key / Value pairs:');
        for (var key in c) {
            console.log("The contact's " + key + " is " + c[key] + ".");
        }
        console.log(' ');
    });

    // Display Contacts
    console.log('There are ' + contacts.length + ' contacts in the contacts Array:');
    var len = contacts.length;
    for (var i = 0; i < len; i++) {
        console.log(contacts[i]);
    }
}

// clear users from local storage
//window.localStorage.removeItem('contacts');