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

Leveraging AngularJS $filter in conjunction with ng-disabled

I have a variable in my $scope that contains information about an election, including a list of voters with unique IDs: $scope.election = { voters: [ { _id: '123' }, { _id: '456' }, { _id: '789' } ] } Additio ...

What is the best way to incorporate this into a Vue project?

I am in the process of transitioning my code to Vue.js, so I am relatively new to Vue. In the screenshot provided (linked below), you can see that there are 4 columns inside a div with the class name columns. I attempted to use the index, like v-if='i ...

Guide on setting a property for req.session

I'm a beginner in node.js and sessions, and I am having trouble setting properties to the session! I am trying to add a property to the session and save it in the database, but I keep getting errors. Here are my codes: app.js (main js file) const s ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

methods for transferring information from a website to a smartphone using SMS

I am currently in the early stages of learning JavaScript and working on a project that involves creating a form (a web page) to send data to my mobile device via SMS when the submit button is clicked. However, I am unsure how to transfer data from JavaS ...

Tips for testing a mapbox popup using jasmine testing?

I encountered an issue with my mapbox popup while using jasmine and attempting to write a unit test for it. Here is the function in question: selectCluster(event: MouseEvent, feature: any) { event.stopPropagation(); this.selectedCluster = {geo ...

unable to display items in the navigation bar according to the requirements

Currently, I am in the process of developing an application using reactjs and material-ui. This particular project involves creating a dashboard. In the past, I utilized react-mdl for components and found it to work well, especially with the navbar compone ...

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

Is there a way to restrict the number of times I can utilize slideToggle function?

When I continuously click on a div element in an HTML website that triggers the .slideToggle() method, it will keep opening and closing for as many times as I click. The problem arises when I stop clicking, as the <div> continues to toggle open and c ...

I encountered an issue with my PHP script when trying to interpret a JSON file

I encountered an error stating "requested JSON parsing failed". I have written a PHP script to retrieve data from the server side, but I realized that PHP is not installed. Do you think this is required for the script to run properly? Could this be the r ...

Instantly change the default value with Ajax selection

My current setup involves using Ajax to populate a select HTML element with values from an array returned by PHP. Here is the Ajax code snippet: <script type = "text/javascript"> $(document).ready(function(){ $('#fds_categories&ap ...

several JSON entities within fromJSON

My goal is to utilize the fromJSON() function to parse a .json file containing multiple objects structured in the following way: { "key11": value11, "key12": value12 } { "key11": value11, "key12": value12 } … If I manually enclose the entire file with ...

Displaying mysqli results within a div while incorporating an onclick event for a javascript function that also includes another onclick event for a separate javascript function

I'm struggling to figure out the correct way to write this script. Can someone please guide me in the right direction or suggest an alternative method? I've searched but haven't found any relevant examples. I am fetching information from a ...

Achieving success with the "silent-scroll" technique

I've been struggling to implement the 'scroll-sneak' JavaScript code for quite some time now. This code is designed to prevent the page from jumping to the top when an anchor link is clicked, while still allowing the link to function as inte ...

Having trouble parsing a JSON object using the fetch method in React while trying to retrieve data from my database

While using fetch with the "get" method, I encountered an issue where passing the response from my SQL database to my object using useState results in an empty object. However, when I print the response data from my database through console logs, it shows ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

"Displaying 'Object Object' as a title when hovering over an element

I am currently using an accordion element to display several FAQs on a webpage. The code snippet for the accordion with content is as follows: { Object.keys(FAQS).map((key, index) => { return ( <div key={key}> ...

Issue with Node's jsonwebtoken library: jwt.sign() method fails to include payload in generated token

I am currently working on developing an API with Node.js and have configured const jwt = require('jsonwebtoken') to handle JWTs. However, I am facing an issue where the generated token does not contain the payload information. To troubleshoot thi ...

Tips for shifting a stuck div 200px upward once the bottom of the page is reached while scrolling:

I've set up a page layout with two columns, one fixed and the other scrollable. The left column is fixed (containing Google ads) and stays in place as I scroll down the page. The right column displays posts and scrolls along with the rest of the con ...

Creating a time-limited personal link with Django Rest Framework and React

I have a frontend application built with React Framework that I want to provide access to via a time-limited personal link, without the need for additional authentication functions. With approximately 1-2 new users per day, my proposed implementation is as ...