Mastering the art of extracting JSON key-value pairs using JavaScript

I am looking to extract the key from a JSON file and then populate another select input with the corresponding values using JavaScript.

Below is the structure of my JSON file:

"city": {
"Afghanistan": [
  "Herat",
  "Kabul",
  "Kandahar",
  "Molah",
  "Rana",
  "Shar",
  "Sharif",
  "Wazir Akbar Khan"
],
"Albania": [
  "Elbasan",
  "Petran",
  "Pogradec",
  "Shkoder",
  "Tirana",
  "Ura Vajgurore"
],

The goal is to display only the country names in one select input, and when a user selects a country, all cities belonging to that country should be dynamically loaded into the other input field.

Here is the current HTML code snippet I am working with:

<div class="form-group">
   <label for="Country">Country</label>
   <select class="custom-select" id="Country">
      <option selected>Choose...</option>
   </select>
 </div>
 <div class="form-group">
    <label for="ville">Ville</label>
    <select class="custom-select" id="ville">

    </select>
 </div>

Answer №1

$.getJSON("information.json", function(data){
        $.each(data.country, function(index, value){
             $('#Country').append($('<option>', { 
                text : index 
            }));
        });
});

$("#Country").on("change", function() {
    var selected_country = $(this).val();
    $.getJSON("information.json", function(data){
         $.each(data.city[selected_country], function(index, value){
             $('#City').append($('<option>', { 
                text : value 
            }));
        });
    });

})

This code snippet should do the trick, but you could refactor it for better readability.

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

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

"Having trouble with Set-Cookie Response Header not setting the cookie? It could be due to

My webpage is located at: http://localhost:4201/login When a user clicks on login, it sends a request to: http://localhost:4201/api/login/authenticate This request is then proxied to: The response from the proxy contains a set-cookie header with the f ...

Exploring the Power of jQuery Deferreds and Promises through Multiple getJSON Requests

I'm currently exploring the concept of jquery deferred/promises. I have a decent grasp on how to handle one ajax call, but I'm struggling with managing multiple ajax calls simultaneously. Here is a link to a jsfiddle showcasing my attempt: http:/ ...

Is there a way to obtain HTML code within a contentEditable DIV?

When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked. <div id="MyEditableId" contentEditable="true"> 1. Some text 123. <span style="background-c ...

Trigger an alert when a button is clicked and redirect the user to an newly opened tab

I recently created a button with a link that opens in a new tab. I also implemented some JavaScript to display an alert. Everything is working as expected, but after the user clicks "OK" on the alert, they remain on the same page. I would like to automati ...

Modifying npm packages within a web application

I have a web application where I recently installed an npm package. However, I've realized that I need to customize it by adding some code. My attempt to modify the package directly in node_modules hasn't resulted in any visible changes. Is there ...

Issue with Bcrypt comparison resulting in constant false output

Attempting to implement password verification using bcryptjs, const bcrypt = require('bcryptjs'); login(post){ this.uid = post.uid; this.pin = post.pin; this.getUser(this.uid); if(this.checkUser != undefined ...

The absence of a closing parentheses in the argument is causing an issue when rendering

Apologies for the basic mistake, but I could really use some assistance with this syntax error. I've spent over an hour searching for it and still haven't been able to locate the issue. It seems to be around the success function(data) section. Th ...

The md-items function is experiencing issues with updating the suggestion list correctly within the md-autocomplete feature of Angular Material

I am currently utilizing md-autocomplete, and I am facing an issue with the md-items not updating the response list correctly from the Service Host - Ajax Call. Here is the HTML Source Code: <md-autocomplete flex required md-input-name="autocomple ...

How can I interpret a string with a specific format using JavaScript?

Input String: var json_data = "{0:'apple', 1:'bannana', 2:'guava'}"; Desired Output after parsing with JavaScript: var json_data = { columns: [{0:'apple'}, {1:'bannana'} ,{2:'guava'}] ...

javascript close the current browser tab

Can someone please help me with a JavaScript code to close the current window? I have tried the following code but it does not seem to work: <input type="button" class="btn btn-success" style="font-weight: b ...

JavaScript: What's the best way to update the URL in the address bar without triggering a page refresh?

Similar Question: How can I use JavaScript to update the browser URL without reloading the page? I've observed websites like GMail and GrooveShark altering the URL in the address bar without having to refresh the entire page. Based on my understa ...

Looking for insights on reading and presenting XML files from a URL? Learn how to achieve this effortlessly with the power

Currently, I'm in the process of developing an innovative Android application using PhoneGap. My main objective is to dynamically present the data stored within a customized XML file hosted on my website that follows the .php format. Do you happen to ...

Show a checkmark or X depending on the condition in Javascript

I have an array of data that I want to compare to the input in a text field. If the input matches an element in the array, I want to display a checkmark, and if it doesn't match, I want to display a crossmark. However, I'm having an issue where ...

Is it possible to generate a proper JSON string using Bash or Ruby?

I am interested in creating 20 droplets on DigitalOcean, and I want to accomplish this using either Bash or Ruby. Initially, Bash appeared to be the simplest option, but then I realized that JSON is very particular about quotes and requires the -d argument ...

Execute multiple JavaScript files dynamically by utilizing the same npm run command

My directory structure: app Model user.js post.js Contents of my package.json file: "scripts": { "migrate": "node ./app/Model/" } I am looking to execute JavaScript files via command line in a dynamic manner. For example: npm run migr ...

What significance do square brackets hold when initializing arrays in C programming?

static uint8_t togglecode[256] = { [0x3A] CAPSLOCK, [0x45] NUMLOCK, [0x46] SCROLLLOCK }; Can you explain the significance of [0x3A] in the code above? I am familiar with declarations like int a[2] = {1, 2}; but this looks different. ...