Tan Tan - 1 year ago 52
HTML Question

Retrieving values in an object in an array from local storage

I have 2 webpages. One called Create An Event and the other Calendar Of Events. In Create An Event, a form is used to allow users' inputs. The inputs are then stored to local storage with the following function:

document.addEventListener("DOMContentLoaded", docIsReady);
var CreateEvent;

function docIsReady() {
CreateEvent = localStorage.getItem("CreateEvent");
if (CreateEvent == null) {
CreateEvent = [];
} else {
CreateEvent = JSON.parse(CreateEvent);

function saveToStorage() {
var one;
var nameofevent = document.getElementById("name").value;
var pList = document.getElementsByName("pos");
var positions = [];
for (i = 0; i < pList.length; i++) {
//for (i=0; i<positions.length; i++){
var venue = document.getElementById("venue").value;
var date = document.getElementById("date").value;
var starttime = document.getElementById("timeStart").value;
var endtime = document.getElementById("timeEnd").value;
var contact = document.getElementById("contact").value;
var email = document.getElementById("email").value;
var desc = document.getElementById("desc").value;
one = {
"name": nameofevent,
"pos": positions,
"venue": venue,
"date": date,
"timeStart": starttime,
"timeEnd": endtime,
"contact": contact,
"email": email,
"desc": desc
localStorage.setItem("CreateEvent", JSON.stringify(CreateEvent));
return false;

I made CreateEvent an array so as to store the multiple inputs because there cannot be only one event created. Now, I need to display the NAME of the event in a table on Calendar Of Events. As its a calendar, the events will be sorted by the months. However, I don't know how to access the "date" and "name" value in each of the objects stored in the array. How do I retrieve the values in objects?

Answer Source

You index into the array using []:

var entry = CreateEvent[0]; // 0 = the first entry

...and then use the properties on that object:


Side note: You're free to do whatever you like in your own code, but FWIW, CreateEvent is an unusual name for this array for two reasons: 1. It starts with a capital letter, whereas in JavaScript the overwhelming convention is for data variables to start with a lower case letter. 2. It's a verb phrase ("create event"), but its value is a noun (an array of events). Typically lists and arrays are named with the name of what they contain, either in the plural or with a suffix like list or array. So in this case, events or eventList or eventArray would be more standard.