Using ES6 without the need for jQuery, populate a select element with JSON data using Javascript

I have a json-formatted dataset that I want to incorporate into my select options.

Here is the data:

 {
    "timezones": 
    {
        "country": "Africa",
        "tz": "Africa/Abidjan"
    },
    {
        "country": "America",
        "tz": "America/Anguilla"
    }
}

Below is the current select menu:

<select>

    <optgroup label="Africa">
        <option value="Africa/Abidjan">Adak</option>
    </optgroup>

    <optgroup label="America">
        <option value="America/Adak">Anguilla</option>
    </optgroup>

</select>

Is there a way to dynamically populate the select menu with the json data provided, without using jQuery?

Answer №1

One way to achieve this is by using the `appendChild` method along with the `.forEach` method.

let data = {
    "timezones": 
    [{
        "country": "Africa",
        "tz": "Africa/Abidjan"
    },
    {
        "country": "America",
        "tz": "America/Anguilla"
    }]
};
let select = document.getElementById('countrySelect');
data.timezones.forEach(function(item){
  let newOptGroup= document.createElement('optgroup');
  newOptGroup.label=item.country;
  let option=document.createElement('option');
  option.value=item.tz;
  option.text=item.tz;
  newOptGroup.appendChild(option);
  select.appendChild(newOptGroup);
});
<select id="countrySelect">

</select>

Answer №2

In the beginning, your JSON data is considered invalid. The 'timezones' attribute should either be an array or have an index on every object.

Below is the provided data:

let data = {
  "timezones": [
  {
      "country": "Africa",
      "tz": "Africa/Abidjan"
  },
  {
      "country": "America",
      "tz": "America/Anguilla"
  }]
}

Here's how I would populate the options:

data.timeszones.forEach(function(timezone) {
  let optionGroup = document.createElement('optgroup');
      optionGroup.setAttribute('label', timezone.country);

  let option = document.createElement('option');
      option.setAttribute('value', timezone.tz);

  optionGroup.appendChild(option);
  document.getElementById('selectionList').appendChild(optionGroup);
});

Lastly, ensure to assign an ID to your <select> element.

<select id='selectionList'>
    <optgroup label="Africa">
        <option value="Africa/Abidjan">Adak</option>
    </optgroup>

    <optgroup label="America">
        <option value="America/Adak">Anguilla</option>
    </optgroup> 
</select>

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

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

Tips for successfully transferring values or parameters within the Bootstrap modal

How can I create a cancel button that triggers a modal asking "Are you sure you want to cancel the task?" and calls a function to make an API call when the user clicks "Ok"? The challenge is each user has a unique ID that needs to be passed to the API for ...

I'm looking to efficiently convert JSON or GeoJSON data into a Backbone model and then seamlessly transition that model into a Leaflet layer. Can anyone provide guidance on

As I work on refining layer definitions that can be added individually to a collection, my goal is to smoothly render the view or add them to a L.LayerGroup using the leaflet api. However, being new to JavaScript, I am uncertain about how to map the proper ...

Using Next.js Link prefetch feature can lead to unexpected 404 errors on a production website

I'm currently working on a Next.JS blog project where I have created a page to showcase all of my articles. When I render the component, it appears like this: <div> {articles.map((article, index) => { const path = `/magazine/${ar ...

When using a jsonp ajax call, the response is successfully returned as json in Firebug, but unfortunately it

After encountering a jsonp cross domain ajax query, I am facing an issue where the jQuery ajax function's error part is triggered despite receiving a status of 200 OK and a status text of success. Even though I can monitor the response in Firebug and ...

Tally the quantity of data points within jQuery Datatables

Upon navigating to my jQuery DataTable, I aim to showcase the count of Users pending activation. Typically, I would use fnGetData with (this), but since I am not triggering this on a click event and wish to count all entries in the table, I am unsure of ho ...

Incorporate the casper function within the casper.evaluate() method

Is it possible to use the casper function inside casper.evaluate() with jQuery code? I need to iterate through elements in a way similar to how jQuery does. I have loaded the jquery.js library. Here is the script I have tried: casper.evaluate(function() ...

The encoding for double quotation marks vanishes when used in the form action

I am attempting to pass a URL in the following format: my_url = '"query"'; when a user clicks on a form. I have experimented with encodeURI and encodeURIComponent functions as well as using alerts to confirm that I receive either "query" or %2 ...

The term 'Buffer' is not recognized in the context of react-native

Having trouble using buffer in my react-native app (developed with the expo tool). I have a hex value representing a geography Point like this for example -> 0101000020E61000003868AF3E1E0A494046B3B27DC8F73640 and I'm attempting to decode it into l ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Using PHP to access Steam API data in JSON format

I am not very familiar with PHP and I am unsure about how to access a specific element of the Steam API JSON. The JSON Output is... { "response": { "players": [ { "steamid": "76561198059606697", "communityvisibilitysta ...

Executing a curl POST request within an npm script

I recently added a new script to my npm scripts in the package.json file, but I'm running into issues due to the single and double quotes. The problem seems to be with the internal double quotes within the payload. "slack": "curl -X POST --data-urlen ...

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Balancing asynchronous tasks - masteringlearnode - program that initially succeeded but eventually faltered

node version: v4.4.3 npm version: 3.8.9 Error output Your entered data does not match the expected values. ──────────────────────────────────────────────── ...

Issue encountered while trying to display Twitter search outcomes

My apologies in advance for what may seem like a simple question, but I cannot seem to wrap my head around this issue. I would greatly appreciate any insights into why the following error is occurring within my codebase and for any other potential mistakes ...

java JSON responses containing long values that have been rounded

Upon receiving a JSON response from my RESTful service developed in Java, I have noticed that long data type values ending with 01 are being rounded down to 00. Allow me to provide examples: For instance, 12345123459876501 is returned as 1234512345987650 ...

URL for requesting JSON data using Zend Framework

Just getting started with ZF1 and I'm tackling the task of obtaining a JSON response for a specific id. I have successfully retrieved all values from a table using the code below. The question now is, how can I pass a parameter from the URL? public ...

Having trouble with the click button flip function? It seems to be working in one section but not in

Currently, I am facing an issue with a card section that contains two buttons and a description. The first button adds an image which is working perfectly fine, as well as the description section. On the other hand, the second button adds a video and when ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...