Display JSON information in a table within a dropdown menu

I have a JSON dataset where each key is represented as a column in a table. I am looking to populate each column with data from the JSON as select boxes. For example, I want to display all "country" values from the JSON as select options in the COUNTRY column.

Sample JSON data

"book": [
  {
    "author": "Chinua Achebe",
    "country": "Nigeria",
    "imageLink": "images/things-fall-apart.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    "pages": 209,
    "title": "Things Fall Apart",
    "year": 1958
  },
  {
    "author": "Hans Christian Andersen",
    "country": "Denmark",
    "imageLink": "images/fairy-tales.jpg",
    "language": "Danish",
    "link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
    "pages": 784,
    "title": "Fairy tales",
    "year": 1836
  },

Javascript Code

let table2 = document.getElementById("tr2")

var books = fetch("book.json")
.then(res=> res.json())
.then(data => {for(let key in data ) {
    for(value of data[key]) {

        select.innerHTML+= `
         <td><option value="${value.author}">${value.author}</option></td>
          <td><option value="${value.country}">${value.country}</option></td>
        `
    }
}})

How can I make modifications to this setup?

Answer №1

Is this what you had in mind? First, looping through the keys and then through each item for every key. Finally, aggregating into an array and creating a <select> element using a simple utility function.

var obj = {"book":[{"author":"Chinua Achebe","country":"Nigeria","imageLink":"images\/things-fall-apart.jpg","language":"English","link":"https:\/\/en.wikipedia.org\/wiki\/Things_Fall_Apart\n","pages":209,"title":"Things Fall Apart","year":1958},{"author":"Hans Christian Andersen","country":"Denmark","imageLink":"images\/fairy-tales.jpg","language":"Danish","link":"https:\/\/en.wikipedia.org\/wiki\/Fairy_Tales_Told_for_Children._First_Collection.\n","pages":784,"title":"Fairy tales","year":1836}]}


function createSelect(select, options, name) {
  select.innerHTML = '<option>Choose ' + name + '</options>';
  options.forEach(function(value) {
    var option = document.createElement("option");
    option.setAttribute("value", value);
    option.innerText = value;
    select.appendChild(option)
  })
}

createBookSelects(obj)

function createBookSelects(obj) {

  var books = obj.book;
  var keys = Object.keys(obj.book[0]);
  var result = {}
  keys.forEach(function(key) {
    obj.book.forEach(function(item) {
      result[key] = result[key] || []
      result[key].push(item[key])
    })

    var selectCategory = document.createElement("SELECT");
    selectCategory.setAttribute("id", "category");
    document.body.appendChild(selectCategory);
    createSelect(selectCategory, result[key], key)
  })
}

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

Incorporate href along with ng-click for improved functionality

I need a link that will call a $scope-function when clicked, which will then display another view. I also want the user to be able to right-click on the link and open it in a new window or bookmark it. Unfortunately, the current html code is not worki ...

Guide to saving an http response as a file and automatically retrying on a 503 error

When it comes to piping the response of an http request to a file, the process is pretty straightforward: http.get(url, function (res) { var file = fs.createWriteStream(filename) res.pipe(file) file.on('finish', function () { file.clos ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...

Oops! Looks like Handlebars.js is telling us that a Helper is missing

Currently, I am utilizing handlebars.js templates alongside node and express. My goal is to create a numbered list using the {{@index}} template tag. However, since the index starts at 0 and I want it to start from one, it seems that a custom helper is req ...

Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an object const response = { "message": "story records found successfully", "result": [ { "created_AT": "Thu, 13 Jan 2022 17:37:04 GMT", ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

Struct object not found within nested array during JSON unmarshaling

Encountered an issue with unmarshalling a string back to a struct object that contains a nested array of struct objects. The problem is demonstrated in the following code snippet: The JSON string is as follows: const myStr = `{ "name": "test_session1", ...

What steps can be taken to design a unique CSS pop-up that triggers upon page load, limited to one appearance per visitor every week

I have the following code snippet that allows me to display a pop-up either by clicking on the link or hovering over it. I am looking to modify it so that the pop-up opens when the page loads and restrict it to open only once per visitor per week. As some ...

Looking for a JSON file in bash?

I have a JSON file that I need to extract a specific part from: { "expand": "names,schema", "issues": [ { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "fields": { ...

Retrieve information from a MongoDB document based on the specific month

If I have a user document with a createdAt field, how can I retrieve data by month in the condition? The format of the createdAt value is as follows: 2016-10-08T16:21:40.935Z Account.find({'what should be passed here?'}, function(err,response){ ...

AngularJS fails to display JSON data

I've been experimenting with AngularJS by creating a basic gallery that pulls images from a JSON file, but for some reason I'm having trouble displaying the data. index.html: <!DOCTYPE html> <html ng-app="portfolioApp"> <head> ...

Pressing the switch will not alter its state the initial time, except if it is already selected

As a beginner in React, I have recently started working on developing an admin panel locally to practice and apply my newly acquired knowledge. However, I've encountered a frustrating problem that has me on the verge of stepping on kittens and innocen ...

Ensuring User Information Persistence in React Upon Successful Login

I am developing a small application using React with PHP as the back-end. Within my database, I have two types of users - admin and student. Upon user login, I store their information in session storage like this ( user: { username:'abcxyz123', r ...

In the context of Express, how are "static" and "non-static" defined?

The Express documentation explains that the express.static() middleware is used to serve static files like images, CSS, and JavaScript. However, when serving a front-end React app using express.static("some_build_dir"), which includes JS files ...

Can data sent to php via ajax be manipulated?

To restrict the number of characters a user can input in a textarea, I have implemented a character counter. // part of tinymce setup: function (ed) { ed.on('keyup', function (e) { var maxchars = <?php echo $max_chars_allowed; ?>; ...

The issue with VueEditor in Nuxt.js is that it's throwing an error

When working on my Nuxt.js project, I integrated the vue2-editor package for writing articles with HTML. Everything functions properly when I enter text and submit it, however, upon reloading the page, I encounter an error stating "document is not defined" ...

Utilizing window.prototype methods in JavaScript for Angular development

I have been tasked with migrating AngularJS code to Angular. There is a JavaScript function that needs to be integrated into an angular component, and the project is using Angular version 12+. The JavaScript function in question is as follows: (function(wi ...

Capturing screenshots with Selenium in Node.js is proving to be quite sluggish

My current project involves using Selenium with Mocha in Node.js for UI testing on a website. I want to capture screenshots after each test to review and share the results visually. The challenge arises when there are AJAX calls and JavaScript animations ...

Accessing component variables within an event in Angular 2 (dealing with scope problems)

I am currently facing an issue with scoping in my component click event. Specifically, I need to access private variables within the component, but the keyword this now refers to the event scope rather than the component's. This has led to an error wh ...

I am encountering an issue with my curl HTTP POST request where it is fetching a PDF file, but the

After attempting to send a PDF file through Twilio API in WhatsApp using curl POST, I noticed that the file was being sent without its proper file name and appeared as "untitled". Despite ensuring that all metadata and properties were accurately filled in, ...