What is the process for including a new item in a JavaScript dictionary?

I'm currently learning JavaScript and I've encountered a challenge. I have a dictionary that I'd like to update whenever a button is clicked and the user enters some data in a prompt. However, for some reason, I am unable to successfully update the dictionary.

    "use strict"

let views = {View1:"From localStorage"};

let btn = document.getElementById("myBtn")
btn.addEventListener("click",function(){
    let vname = prompt("What is the name of the new view?")
    views[vname] = vname + " 77"
})

let views_ser = JSON.stringify(views)
localStorage.setItem("views",views_ser);

let views_deser = JSON.parse(localStorage.getItem("views"))

for (let keys in views_deser){
    document.write(keys + "<br>")
    document.write(views_deser[keys]+ "<br>")
}

Appreciate any help on this. Thank you.

Answer №1

This is not an answer, as you have already correctly solved it yourself, but I want to showcase the use of SO snippets. To focus on the topic of "adding something to a dictionary," here is a demonstration of the initial part of your code:

let views = {View1:"From localStorage"};

let btn = document.getElementById("myBtn")
btn.addEventListener("click",function(){
let vname = prompt("What is the name of the new view?")
views[vname] = vname + " 77"
console.log(views); // display current status of the "views" dictionary
})
<button id="myBtn">add view</button>

Answer №2

"use strict";

const data = {Entry1:"Initial data"};

const button = document.getElementById("myButton")
button.addEventListener("click",function(){
    let itemName = prompt("Enter the name of the new item:")
    data[itemName] = itemName + " 77"
    updateList("dataList");
})

const updateList = (listContainerID) => {

 const list = document.getElementById(listContainerID)
 if(!list){
  return;
 }
 
 let listHTML = '';
 
 Object.keys(data).forEach( key => {
      listHTML += `<li>${key}: ${data[key]}</li>`;
 });
 
 list.innerHTML = listHTML;

}

updateList("dataList");
<button id="myButton">Add</button>

<hr>

<ul id="dataList"></ul>

Ensure to refresh the list every time a new item is added. To achieve this, encapsulate the "list updating logic" within a function that can be invoked whenever an item is added (and once during initialization).

In this demonstration, due to limitations concerning localStorage, I opted for simply utilizing a variable for storage. However, the same functionality would apply seamlessly with localStorage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Duplicate user scrolling input within a specified div container

I am attempting to recreate a horizontal scrolling effect on a div element that mirrors the input scroll. When the user scrolls along the input, I want the div element to scroll in sync. The issue I am encountering is specific to Chrome, where the input b ...

Monitor changes in the select tag to display the updated value and output

I am new to using jQuery. While I have practiced using native PHP Ajax in the past, I now recognize the need to learn jQuery due to current technological advancements and demands. When the select tag changes, I send the "types" value via POST method to a ...

Challenges in creating an alternative path in ExpressJS

I am currently working on a website for my studies. I decided to use nodejs/Express, as the technology is free. The first route /home was successful, but I am having trouble creating more routes. Although I thought I had a good understanding of the system ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

Interfacing Electron Frontend with Python Backend through seamless communication

Upon completing the development of a Python CLI app, it became apparent that creating an Electron frontend for better user interaction was necessary. What is the best way for the Electron app to communicate with the Python app when a user action occurs on ...

Unable to access MongoDB documents using NodeJS/Express

I can't seem to figure out why I am not receiving any results from a GET call I am testing with Postman. Let's take a look at my server.js file: const express = require("express"); const mongoose = require("mongoose"); const ...

What is the best way to utilize $(target) within a directive?

I created a custom directive for selecting time using two blocks. The challenge is detecting the target event on specific blocks within the directive's template. Directive Template: <div class='time-picker-container'> <div clas ...

Utilizing strings as data in Google charts with jQuery

When working with google charts, the code for generating a chart often looks something like this: var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices&apo ...

The function will provide the value prior to the execution of the Jquery image loading

if (DataService.Validation(file)) { //angularjs call to api controller }; //DataService Validation: function (file) { var Url = URL.createObjectURL(file); var img = new Image(); $(img).load(function () { var imgwidth = this. ...

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

In WildFly, there is a clash of jackson-jaxrs providers when deploying an EAR file

Our Java EE 7 application is currently running on WildFly 9, with an exploded EAR deployment setup that includes several WAR files, some JARs at the EAR level, and a lib folder containing third-party JARs. Although this may not be the recommended approach ...

Unusual issue in IE causing rendering problems in reporting services

Currently, I am creating a report using Reporting Services 2008, MVC 2, and Ajax as my development technologies. When I generate the report, everything displays perfectly if there is data present. However, if there is no data, the report body gets cut off ...

Sending parameters to a personalized Angular directive

I am currently facing a challenge in creating an Angular directive as I am unable to pass the necessary parameters for displaying it. The directive code looks like this: (function () { "use strict"; angular.module("customDirectives", []) .directive ...

When using v-select to search for items, the selected items mysteriously vanish from

I recently worked on a project where I encountered a similar situation to the one showcased in this CodePen. Here is the link to the specific CodePen One issue I faced was that the selected items would disappear when performing an invalid search. After i ...

Functionality of setExtremes ceases to function post initial loading

Initially, the setExtremes function works fine for the chart. However, when I switch pages or reopen the chart with a new JSON file, the setExtremes function stops working and fails to update the min and max values. Any idea why this could be happening? yA ...

Using AJAX to retrieve a specific JSON object from an array of JSON data

Data retrieved in JSON array from the API: [{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}] Using Ajax: $.ajax({ url: 'interface_API.php', ...

NodeJS: Extract images based on specified coordinates

Dealing with images that contain text can be a challenge, but by using tesseract and the imagemagick node module, I was able to extract the text successfully. The only issue I encountered was related to the image size. Fortunately, cropping out the releva ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...