Store object to localStorage Code Snippet

The code defines two functions, addToStorage() and viewStorage(), that interact with the localStorage object in the browser.

The addToStorage() function retrieves the values entered in two form fields using the getElementById() method, and creates an object called myObj with these values as properties. It then logs this object to the console using console.log().

Next, the function converts the myObj object to a JSON string using JSON.stringify() and stores it in localStorage using the setItem() method, with the key “tester”. It also logs the stringified object to the console using console.log().

Finally, the function logs a message to the console indicating that it is adding from storage, along with the type and stringified version of the object.

The viewStorage() function retrieves the item with the key “tester” from localStorage using the getItem() method and assigns it to a variable called tempHolder. It then logs a message to the console indicating that it is viewing from storage, along with the type and stringified version of the object.

Finally, the function parses the tempHolder string into an object using JSON.parse() and logs the resulting object to the console using console.log().

In summary, these two functions allow you to store an object in localStorage and retrieve it later, using JSON to serialize and deserialize the object.

function addToStorage() {
  let tempFirst = document.getElementById('firstName').value;
  let tempLast = document.getElementById('lastName').value;
  let myObj = {"first": tempFirst, "last": tempLast};
  console.log(myObj);
  localStorage.setItem('tester', JSON.stringify(myObj));
  console.log('added to storage ' + JSON.stringify(myObj));
  console.log("adding from storage, type: " + typeof(myObj) + ", " + JSON.stringify(myObj));
}

function viewStorage() {
  let tempHolder = localStorage.getItem('tester');
  console.log("viewing from storage, type: " + typeof(tempHolder) + ", " + tempHolder);
  console.log(JSON.parse(tempHolder));
}

This code will store the object as a string in localStorage using JSON.stringify() and retrieve it as an object using JSON.parse(). It will also log the object as a JSON string to the console for easier viewing.