Click here to Skip to main content
14,173,165 members
Click here to Skip to main content
Add your own
alternative version

Stats

1.6K views
4 bookmarked
Posted 14 May 2019
Licenced CPOL

Managing Key-Value Stores with JavaScript's LocalStorage API

, 14 May 2019
Rate this:
Please Sign up or sign in to vote.
We show how to deal with key-value pairs and how to manage a key-value store using JavaScript's localStorage API.

This article is a section from the book Information Management - An Introduction to Information Modeling and Databases.

In a key-value store, the information items are formed by key-value pairs like the phone number directory entry ⟨"Bob", "(732) 516-8970"⟩ or the English-German translation table row ⟨"my car", "mein Auto"⟩.

Well-known key-value store management systems are Redis, Oracle Berkeley DB and the localStorage that is built into the Web programming language JavaScript.

The key in a key-value pair must be unique. Normally, keys are strings. But a key-value DBMS may allow any value supported by the DBMS (strings, numbers, object references, etc.) to be a key. Normally, the value in a key-value pair may be any value supported by the DBMS.

We show how to deal with key-value pairs and how to manage a key-value store using JavaScript, which provides a built-in object called localStorage that allows storing a key-value pair in the following way:

localStorage["Bob Jennings"] = "(732) 516-8970";

JavaScript programs are loaded and executed in the context of a webpage defined with HTML (the ). In our key-value store project, we embed the JavaScript code within the HTML files index.html, add.html, update.html, and delete.html, corresponding to the data management operations Retrieve/List All, Create/Add, Update and Delete. All of these HTML files contain the same navigation menu (in a nav element), allowing to go to any of these pages for performing the corresponding data management operation.

2.1. Retrieving All Key-Value Pairs and Listing Them in a Table

The following HTML code contains a heading (the h1 element), an empty table that will be filled with the help of JavaScript code, a navigation menu (in the nav element), and a script element containing the JavaScript code.

  1  <!DOCTYPE html>
  2  <html xmlns="http://www.w3.org/1999/xhtml">
  3  <head>
  4   <meta charset="UTF-8" />
  5   <title>Phone Number Directory</title>
  6  </head>
  7  <body>
  8   <h1>Phone Number Directory</h1>
  9   <table>
 10    <tbody id="directory"></tbody>
 11   </table>
 12   <hr/>
 13   <nav>
 14    <ul>
 15     <li><a href="index.html">Home</a></li>
 16     <li><a href="add.html">Add an entry</a></li>
 17     <li><a href="update.html">Update an entry</a></li>
 18     <li><a href="delete.html">Delete an entry</a></li>
 19    </ul>
 20   </nav>
 21   <script>
 22    ...
 23   </script>
 24  </body>
 25  </html>

On this "Home" page of our data management app, the currently stored key-value pairs are retrieved from localStorage and shown as table rows. If localStorage is empty, four test data key-value pairs are created and added to the store. This is done by the following JavaScript code, which forms the content of the script element:

  1  <script>
  2   // get a handle for accessing the "directory" table body element
  3   let tableBodyEl = document.getElementById("directory");
  4   // add some key-value pairs if the store is empty
  5   if (localStorage.length === 0) {
  6     localStorage["Bob Jennings"] = "(732) 516-8970";
  7     localStorage["Jane Anselm"] = "(732) 516-4301";
  8     localStorage["Tara Helms"] = "(504) 972-3381";
  9     localStorage["Tom Miller"] = "(282) 664-9357";
 10   }
 11   // show the contents of the store
 12   for (let key of Object.keys( localStorage)) {
 13     let row = tableBodyEl.insertRow();
 14     row.insertCell().textContent = key;
 15     row.insertCell().textContent = localStorage[key];
 16   }
 17  </script>

Exercise: Open a text editor of your choice (e.g., NotePad++). First copy and paste the HTML code above into your editor, then add the JavaScript code in the script element. Make a folder (e.g. with name "KeyValueStoreExample") and save the content of your editor window in this folder as "index.html". Then go to this folder (e.g., using Windows Explorer) and open the "index.html" file in a browser. You should see a page containing a table with 4 phone directory entries as in Table 1-1 above.

2.2. Adding a Key-Value Pair in a User Interface

The following HTML code contains a form element (instead of a table) for allowing the user to enter new key-value pair data in a user interface. The navigation menu (in the nav element) is the same as above and is therefore omitted.

The form-based user interface consists of two labeled input fields (named "key" and "value") and a Save button. Each user interface element is contained in an HTML p element that defines a layout block for it.

  1  <!DOCTYPE html>
  2  <html xmlns="http://www.w3.org/1999/xhtml">
  3  <head>
  4   <meta charset="UTF-8" />
  5   <title>Phone Number Directory</title>
  6  </head>
  7  <body>
  8   <h1>Phone Number Directory</h1>
  9   <h2>Add an entry</h2>
 10   <form>
 11    <p><label>Name: <input name="key"/></label></p>
 12    <p><label>Phone no.: <input name="value"/></label></p>
 13    <p><button type="button" onclick="save()">Save</button></p>
 14   </form>
 15   <hr/>
 16   <nav>...</nav>
 17   <script>
 18    function save() {
 19      let formEl = document.forms[0];  // the 1st form on the page
 20      localStorage[formEl.key.value] = formEl.value.value;
 21    }
 22   </script>
 23  </body>
 24  </html>

The script element only contains the JavaScript code of the save function, which adds the key-value pair entered in the form fields "key" and "value" to the localStorage database.

Exercise: Copy and paste the HTML code, including the script element with its JavaScript code, into a fresh editor window. Don't forget to insert the content of the nav element from the previous subsection. Then save the content of the editor window in your example folder as "add.html". Then open the "add.html" file in a browser. You should see a page containing a user interface as in Figure 2-1 below. Add a name and a phone number and click the Save button. Then click on Home in the menu for checking if your new key-value pair has been added to the store.

Figure 2-1. The user interface of the key-value data management app for the operation Add.

2.3. Deleting a Key-Value Pair

For allowing the user to delete a key-value pair entry from the store, the user interface must provide a facility for choosing the entry to be dropped. For this purpose, HTML provides the select element, which is rendered as a selection field that can be expanded to a list of options to choose from.

The Delete user interface consists of a labeled selection field (named "key") and a Delete button.

  1  <!DOCTYPE html>
  2  <html xmlns="http://www.w3.org/1999/xhtml">
  3  <head>
  4   <meta charset="UTF-8" />
  5   <title>Phone Number Directory</title>
  6  </head>
  7  <body>
  8   <h1>Phone Number Directory</h1>
  9   <h2>Delete an entry</h2>
 10   <form>
 11    <p><label>Name: <select name="key"></select></label></p>
 12    <p><button type="button" onclick="destroy()">Delete</button></p>
 13   </form>
 14   <hr/>
 15   <nav>...</nav>
 16   <script>...</script>
 17  </body>
 18  </html>

The following script element contains the JavaScript code for filling the selection list with option elements and the code of the destroy function, which deletes the selected key-value pair both from the localStorage store and from the selection list.

  1  <script>
  2   // get a handle for accessing the form element
  3   let formEl = document.forms[0];
  4   // get a handle for accessing the "key" selection field
  5   let selectEl = formEl.key;
  6   // fill selection list with options
  7   for (let key of Object.keys( localStorage)) {
  8     let optionEl = document.createElement("option");
  9     optionEl.text = key;
 10     selectEl.add( optionEl, null);
 11   }
 12   function destroy() {
 13     // delete from key-value store
 14     localStorage.removeItem( selectEl.value);
 15     // delete also from selection list
 16     selectEl.remove( selectEl.selectedIndex);
 17   }
 18  </script>

Exercise: Copy and paste the HTML code into a fresh editor window. Don't forget to insert both the content of the nav element (from a code listing above) and the content of the script element. Save the resulting user interface page in your example folder as "delete.html". Then open the "delete.html" file in a browser. You should see a page containing a user interface as in Figure 2-2 below. Choose a name and click the Delete button. Then click on Home in the menu for checking if the chosen key-value pair has been deleted from the store.

Figure 2-2. The user interface of the key-value data management app for the operation Delete.

2.4. Updating a Key-Value Pair

The Update user interface consists of a labeled selection field (named "key") for choosing the entry to be updated, an input field (named "value") for entering the value (the phone number), and a Save button.

  1  <!DOCTYPE html>
  2  <html xmlns="http://www.w3.org/1999/xhtml">
  3  <head>
  4   <meta charset="UTF-8" />
  5   <title>Phone Number Directory</title>
  6  </head>
  7  <body>
  8   <h1>Phone Number Directory</h1>
  9   <h2>Update an entry</h2>
 10   <form>
 11    <p><label>Name: <select name="key" onchange="fillForm()"></select></label></p>
 12    <p><label>Phone no.: <input name="value"/></label></p>
 13    <p><button type="button" onclick="save()">Save</button></p>
 14   </form>
 15   <hr/>
 16   <nav>...</nav>
 17   <script>...</script>
 18  </body>
 19  </html>

The following script element contains the JavaScript code for filling the selection list with option elements and the code of the functions fillForm and save. The function fillForm is called when a name has been chosen in the selection field. The save function assigns the updated value from the input field to the selected key in the localStorage store.

  1  <script>
  2   // get a handle for accessing the form element
  3   let formEl = document.forms[0];
  4   // get a handle for accessing the "key" selection field
  5   let selectEl = formEl.key;
  6   // fill selection list with options
  7   for (let key of Object.keys( localStorage)) {
  8     let optionEl = document.createElement("option");
  9     optionEl.text = key;
 10     selectEl.add( optionEl, null);
 11   }
 12   // fill form when an entry has been selected
 13   function fillForm() {
 14     formEl.value.value = localStorage[selectEl.value];
 15   }
 16   // save in key-value store
 17   function save() {
 18     localStorage[selectEl.value] = formEl.value.value;
 19   }
 20  </script>

Exercise: Copy and paste the HTML code into a fresh editor window. Don't forget to insert both the content of the nav element (from a code listing above) and the content of the script element. Save the resulting user interface page in your example folder as "update.html". Then open the "update.html" file in a browser. You should see a page containing a user interface as in Figure 2-3 below. Choose a name such that the associated phone number is shown. Change this phone number and click the Save button. Then click on Home in the menu for checking if the chosen key-value pair has been updated.

Figure 2-3. The user interface of the key-value data management app for the operation Update.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gerd Wagner
Instructor / Trainer
Germany Germany
Researcher, developer, instructor and cat lover.
Co-Founder of http://web-engineering.info

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190524.3 | Last Updated 15 May 2019
Article Copyright 2019 by Gerd Wagner
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid