Change a table containing select fields into a JavaScript array

I have created a table using data from a parsed CSV file. The table consists of two columns - one for extracted values and the other for dropdown selection. However, I am struggling to extract the values selected in the dropdown fields. Can anyone assist me with this?

In my HTML code, the table structure looks like this:


            function extractTable() {
                var csvTable = document.querySelector("#csv_table");
                var newTableObj = [];
                var tableRows = [].reduce.call(csvTable.rows, function(res, row) {
                    res[row.cells[0].textContent] = row.cells[1].textContent;
                    return res;
                }, {});
                delete tableRows['Column value']; // Removes the header row

                // Create an object
                newTableObj.push(tableRows);
                console.log(newTableObj);

                // Create a JSON
                let jsonTable = JSON.stringify(tableRows, null, 2);
                console.log(jsonTable);
            };
        
    

If you'd like to view an example on CodePen, here is the link: https://codepen.io/AllenT871/pen/XoazJz?editors=1011#

Any assistance or feedback would be greatly appreciated.

Answer №1

Consider utilizing document.getElementsByClassName or document.getElementsByTagName to access specific table elements instead of fetching the entire table structure.

After obtaining the desired selectors, you can loop through them to retrieve their values sequentially, bear in mind that they are not iterable and cannot be manipulated using map or reduce.

I trust this information proves beneficial for your task.

The complete code is presented below:

function extractTableData() {
    var selectedItems = document.getElementsByClassName("field_select");
    var selectedValues = [];       

    for(var i = 0; i<selectedItems.length; i++){
      var element = selectedItems[i];
      var value = element.options[element.selectedIndex].value;
      console.log(value);
      selectedValues.push(value);
    }

    // Generating a JSON object
    let jsonResult = JSON.stringify(selectedValues, null, 2);
    console.log(jsonResult);
};

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

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

Using Ajax with Controller Action in Yii2

As a newcomer to programming, I am facing an issue where I need to call a function when the user inputs data and clicks the submit button. Although I am working with Yii2, I lack experience in Ajax. Despite my efforts, the controller action is not being tr ...

What action will prompt the event to export all data as a CSV file?

After exploring various suggestions on stackoverflow related to my question, I have not been successful. My current challenge involves implementing server-side pagination in UI-GRID. I am specifically struggling with exporting all data as a CSV file. Due ...

Exploring the consumption of jQuery with ASP.net web services

Recently, I have been exploring how to consume a webmethod using the $.ajax call with the following code snippet: $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "WebService.asmx/HelloWorld", ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

What are the differences between incorporating JavaScript directly into HTML and writing it in a separate file?

I need help converting this JavaScript embedded in HTML code into a standalone JavaScript file. I am creating a toggle switch that, when clicked, should go to a new page after the transformation. I am looking for the non-embedded version of the function. H ...

Loading Angular Controller in a dynamic fashion

I am attempting to dynamically load controllers using ocLazyLoad: $ocLazyLoad.load('./ctrls/login.js'); However, I am encountering an error stating: The controller named 'loginCtrl' is not registered. angular.module('opt ...

gathering identical objects in the collection

I need to calculate the total time of the specified objects and display it in a single list. Here is the object data: var list = [ { 'user': 'Tom', time: 270547 }, { 'user': 'Alex', time: 82081 }, { 'user&apo ...

What is the process for removing a property from the prototype within an array of MongoDB objects?

I have a database in MongoDB/Mongoose where I store user information, including passwords. However, when I want to display a list of contacts on the frontend, I don't want to include the passwords for security reasons. To achieve this, I attempted to ...

Ajax experiences trouble with a intricate sequence of characters

How can I successfully send the following string to a spring MVC controller using ajax: (?=^.{8,}$)(?=.+\d)(?=.+[!@#$%^&]+)(?!.*[\n])(?=.+[A-Z])(?=.+[a-z])$ I am encountering a 400 bad request error and it is not leaving the client side. An ...

Unable to set Object[] as an Observable<Object[]>

Currently in the midst of tackling an Angular 4 project, I have been able to troubleshoot most issues on my own so far. However, there is one error that has me stumped. I am attempting to use *ngFor (async) to showcase a list of Observable objects. Despit ...

Exploring the power of MongoDB arrays in combination with AngularJS

How can I insert data into MongoDB using AngularJS's $http service when one of the variables is an array stored in the collection? Variables: - nome: string. - autor: string. - genero: array. - info: string. Collection: mangas. db.mangas.insert({n ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

Identifying particular text patterns in JavaScript using regular expressions

disclaimer - brand new to regular expressions.... I'm facing a challenge with a string that looks like this: subject=something||x-access-token=something The task at hand is to extract two specific values: Subject and x-access-token. To get starte ...

Experiencing repeated occurrences of a problem with Javascript variables

let data; if(post.images.some(img => img._id == doc_id)) { post.images.forEach(function(e,i){ if (post.images[i]._id == doc_id) { data = ..... // defining const data here ensures its block scope is limited to this b ...

Activating/Deactivating Drop-down Menus Depending on Selected Options

I'm attempting to control the enable/disable functionality of two select boxes based on the user's selection in a third box using jQuery. The goal is to enable select box 2 when the user chooses one of the first two options in the controller, and ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

JavaScript load event causing a race condition

Here is the code snippet I've put together. Please excuse any syntax errors, as I typed this out on my phone. export default class Main extends React.Component { componentDidMount() { axios.get('/user?ID=12345') .then(function (re ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

Issue with ng-repeat when using radio buttons

While attempting to utilize radio buttons with ng-repeat, I am encountering issues where the form does not bind correctly and all radio buttons are buggy. What could be causing this issue? Whenever I click on a radio button, either all of them change or no ...