Using JavaScript to create a JSON object within a table

Currently, I am facing a challenge in creating a JSON object from an HTML table using JavaScript. While I can successfully retrieve the values of each cell in JavaScript, the issue lies in organizing and retrieving them as per my requirements. Here is the code snippet that illustrates how I am currently fetching the values:

var x = document.getElementById("tableId");

for (var i = 0; i < x.rows.length; i++) {
    for (var j = 0; j < x.rows[i].cells.length; j++){
            tableJsonDTO[name] = x.rows[i].cells[j].innerHTML;
    }
}

The table structure is as follows:

header:      company_1      company_2      company_3

Question1    answer_1       answer_1       answer_1

Question2     answer_2       answer_2       answer_2

I aim to extract the values to achieve an object structure like this:

var obj = [{spname:"company_1",qalist:[{question:"",answer:""},{question:"",answer:""}]},
           {spname:"company_2",qalist:[{question:"",answer:""},{question:"",answer:""}]},
           {spname:"company_3",qalist:[{question:"",answer:""},{question:"",answer:""}]}]

If you have any suggestions or solutions on how to approach this problem, please share them. Your input would be greatly appreciated.

Answer №1

To efficiently update the values in tableJsonDTO, you just need to adjust how you are assigning them. Check out this helpful demo link.

document.getElementById('toJSON').addEventListener('click', function(){
    var table = document.getElementById('mytable'),
        names = [].slice.call(table.rows[0].cells), 
        values = [].slice.call(table.rows, 1),
        result = {};


    values.forEach(function(row) { //loop through values
        var cells = row.cells,
            title = cells[0].innerHTML; //retrieve property name

        [].forEach.call(cells,function(cell,idx){ //iterate over answers
            var value = {}, 
                arr;
            if(!idx) return; //skip first column

            value[title] = cell.innerHTML; //prepare value

            //obtain or initialize array of values for each name
            arr = result[names[idx].innerHTML] || (result[names[idx].innerHTML] = []);

            arr.push(value); 
        });
    });

    console.log(result);
});

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

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

Stop mega menu items from disappearing when hovered over

I'm currently working on a web page that features a mega menu. When I hover over the mega menu, it displays its items. However, when I try to hover over the items, they disappear. Here is the HTML code snippet: <li class="dropdown mega-dropdown m ...

Implementing Firebase pagination alongside Mui-Datatable pagination and sorting capabilities

I've been trying to implement server-side pagination and filtering for the Mui-Datatable to display my data, but I haven't been successful so far. Here are the snippets of code that I have been working on: One issue that I'm facing is that ...

I am feeling quite lost in trying to figure out how to create a voice mute command using Discord

I've been searching for information on how to create a command that mutes only one specific person I tag in chat, but I'm having trouble finding any guidance on it. As someone new to discord and node js, I could really use some assistance. Mute ...

Error caught: The `onClick` listener was anticipated to be a function, but instead, it was found to be of type `object` in

While attempting to delete a customer entry with a specific id, I encountered an issue in my customers.js file. Despite adding a delete function, the entry was not being removed successfully. The console displayed the following error: caught Error: Expec ...

Javascript problem involving multiple scopes in closures

What is the most effective solution for addressing this issue related to closure in JavaScript? Here is a simple problem I am facing: I have 10 spans with onclick events (I want an alert showing the number of the span clicked on each click): var spans = ...

The data retrieved in JSON format appears to be corrupted and

I've been experimenting with an API that retrieves data from my database in JSON format. In phpMyAdmin, the sentences appear perfect when I use utf8_general to input a CSV file. For example: A line that includes 'r and special characters etc ...

What are the steps to execute a file on localhost using an HTML page?

Currently, I have an HTML file that leverages the Google Calendar API javascript to read the next event on my calendar. The functionality works flawlessly when manually inserting a specific URL in a browser address window, which triggers a GET request in a ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...

Submitting Forms with XMLHttpRequest

I'm trying to utilize XMLHttpRequest in order to retrieve the response from a remote PHP file and showcase it on my webpage. The issue I'm facing is that the form's data isn't being submitted to the remote PHP page. Any suggestions on ...

Troubleshooting problem in Python/Django: JSON parsing issue on the server

My setup involves a Django server API hosted on PythonAnywhere, along with a client.py file on my local computer. The main goal of the program is to check the stock of a specific item by accessing the database through the API. When the client.py file is ...

Missing ng-required fields not displaying the has-error validation in AngularJS forms

While editing any part of their address, the user should see a red invalid border around each field to indicate that the full form is required. However, for some reason I can't seem to get the 'Address' field to display this border. The set ...

What is the most efficient method for quickly adding rows to a sqlite database?

I'm currently working on inserting approximately 7000 rows into an Android Galaxy Tab2's sqlite database. Right now, I am parsing a JSON file and using a "for" loop to insert each row into the database. However, this process is taking more than 1 ...

Using jQuery to create a dropdown select menu that displays JSON data for each state in the

Here is the JSON data that has been returned: ({"Data":{"Alabama":"AL","Alaska":"AK","Arizona":"AZ","Arkansas":"AR","California":"CA","Colorado":"CO","Connecticutt":"CT","Delaware":"DE","Florida":"FL","Georgia":"GA","Hawaii":"HI","Idaho":"ID","Illinois":" ...

Accessing HTML elements that are created dynamically in AngularJS

I am facing an issue where I cannot access a function within a newly created DOM element. Despite my best efforts, I can't seem to figure out what is causing this problem. $scope.createCustomHTMLContent = function(img, evtTime, cmname, evt, cust, ser ...

Is it possible to use export default Enum in TypeScript?

I am facing an issue with exporting an enum object as default at the top level in my code. Here is what I tried: export default enum Hashes{ FOO = 'foo', BAR = 'bar', } However, this resulted in an error message: Module parse failed ...

Having trouble with the CSS positioning of divs created with JavaScript: it's not behaving as anticipated

Let me start by saying I have always struggled with CSS positioning. It seems like I am missing something simple here... So, I have a JS script that generates divs within a parent container called #container which is set to absolute position. Here is the ...

Enabling JavaScript functions to accept a variable number of arguments

I am looking to enhance the versatility of the function below by enabling it to accept multiple callbacks to other functions if they are specified in the arguments. $(function() { function icisDashBox(colorElem, thisWidth, thisHeight, completeCallBack ...