Locate the table information stored within a nested array structure

I want to extract data from a table and save it in an array, with each row of the table becoming a sub-array. The HTML structure is as follows:

<table id="contactlisttable">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Phone</th>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Joey</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Anthony</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
</table> 

etc...

This is the code that I am using:

jQuery(document).ready(function(){
    $(function(){
        var $table = $("#contactlisttable"),
        $headerCells = $table.find("tr th"),
        $myrows = $table.find("tr");

        var headers = [],
            rows = [];

        $headerCells.each(function() {
            headers[headers.length] = $(this).text();
        });

        $myrows.each(function() {
            $mycells = $myrows.find( "td.contactlist" );
            cells = []
            $mycells.each(function() {
                cells.push($(this).text());
            });
            if ( cells.length > 0 ) {
                rows.push(cells);
            }  
        });
        console.log(headers);
        console.log(rows);
    }); 
});

The current output of my code is:

[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],

The desired output should be:

["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]

Answer №1

In my opinion, we can simplify this code:

Check out the Live Demo here

JavaScript:

$(function(){
    var results = []; 
    var row = -1; 
    $('#contactlisttable').find('th, td').each(function(i, val){
        if(i % 3 === 0){ //New Row? 
            results.push([]); 
            row++; //Increment the row counter
        }
        results[row].push(this.textContent || this.innerText); //Add the values (textContent over innerText)       
    }); 
    console.log(results); 
}); 

UPDATE:

I have discovered an improved solution that is compatible with IE9 and above. It handles variable row lengths better compared to the previous one.

View the Enhanced Live Demo here

JavaScript:

//IE9+ compatible workaround
$(function(){
    var results = [], row; 
    $('#contactlisttable').find('th, td').each(function(){
        if(!this.previousElementSibling){ //New Row?
            row = []; 
            results.push(row); 
        }
        row.push(this.textContent || this.innerText); //Add the values (textContent preferred over innerText)       
    }); 
    console.log(results); 
}); 

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

Developing a function to handle form submissions using ajax

I need help creating a function to send $_POST data using ajax. I tried the following code but it's not functioning properly. function sendData(variable, value){ var e = value; bar = variable; $.ajax({ type: 'POST&a ...

I want to use React Bootstrap and Next.js to retrieve the text from a textbox in a React Component and then send it back to my Index.js file. How can I accomplish this task?

I need some assistance. Currently, I am facing a challenge. I am trying to retrieve data from one of my React Components named ParameterList. This component contains a React-Bootstrap Form.Control element for numerical input. My goal is to take the value ...

Utilizing the setInterval function within the componentDidMount lifecycle method in React

I am facing a challenge in updating the state of a React component every 1000 ms. I attempted to use setInterval in the componentDidMount method, but encountered issues. Currently, when I log the results, I see an empty state object in the constructor and ...

Error: Attempting to access the 'name' property of an undefined variable is resulting in a TypeError in Material UI

When attempting to display the retrieved data on MUI Autocomplete, I encountered an error that I cannot seem to figure out. The data is fetched from MongoDB, and I simply want to showcase the category names as selectable options. https://i.sstatic.net/cxT ...

Replace every item in the array with the corresponding value from the output and add a line break

I need help creating a flow in PowerAutomate that will go through each value in an array and insert a linebreak after each value found in the output. For example, if I have an array [1, 2, 3] and the input is "Hello 1 nice 2 see you 3 today," I want the ou ...

Learn the steps to import and utilize individual BootStrap 5 JavaScript Plugins

I am currently diving into the world of Bootstrap (v5.1.0) and gulp, but I'm a bit confused about how to import specific Bootstrap JavaScript plugins. I attempted to bring in only the modal plugin from Bootstrap, but encountered either a syntax error ...

Converting JSON object to an array or list using deserialization

I'm not sure what to ask, so I apologize if this is poorly thought out. The other questions I have found are about people receiving object arrays in JSON. Instead of an array, my JSON string is returning as an object. This is new for me because I hav ...

Error triggered by unhandled Promise Rejection when performing Mongoose findOne operation linked to another document

I am using a MongoDB database for my application, and within it, I have a collection dedicated to storing pay band data for specific employee grades. Currently, I am encountering an issue where I am trying to retrieve the pay band information for a particu ...

Transforming dynamic tables into JSON format

Whenever a user adds a new row to the dynamic table to input customer information, I require the data to be submitted in JSON format upon clicking the submit button. HTML <table class="table table-bordered table-hover" id="driver"> ...

calculating the rotation angle from the origin to a vector within a three-dimensional space using three.js

I am working with a vector in three-dimensional space. Is there a method to determine the angle of rotation from the origin to this vector on each axis? For example, if the vector is located at x=6, y=-10, z=20, what angle does the vector make with resp ...

Display a video modal upon page load, allowing users the option to click a button to reopen the modal

Looking for a way to make a video modal automatically open on page load and allow users to reopen it by clicking a button? Here's a snippet of code that might help you achieve that: HTML <html> <head> <link rel="stylesheet ...

Refining the options in security question dropdown menus

Firstly: The title should mention filtering security options in dropdown lists, but it seems I'm restricted from using the term questions or question in the title. I came across this code example, but it appears to be outdated. Does anyone know why a ...

What are the steps to retrieve information from a REST API with basic authentication?

I am attempting to retrieve data from a website using the HTTP GET method. This particular website requires basic authentication and the data is in JSON format. You can find the REST API website here: () // Insert your code here angular.module(&apos ...

Building an array of ids that contain the checkbox type using jQuery: What's the best way?

Below is the HTML snippet I am working with: <!-- Parent checkbox code goes here --> <input id="ckbCheckAll" class="custom-check ez-hide" type="checkbox" name=""></input> <!-- Child checkbox codes follow --> <input id="practice_ ...

Using commands like `yarn add` or `npm install --save` does not actually install packages directly to the local project

Recently, I decided to take over the maintenance of a React Native-derived framework project that the original author had abandoned. Along with this project, the original author had also created an installer script for the framework, which I also forked. ...

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

Is there a way to streamline the form completion process on my website by utilizing voice commands through the user's microphone?

My webpage features a web form using Flask where users manually input their information that is then added to a table upon submitting. The current setup involves an autoplay video prompting users with questions, which they answer manually and then submit t ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

What is the process for invoking a server-side function from the client-side in an ASP.NET application?

My website includes an ASP.NET button control and a textbox. I need to set up a confirm message box that will appear when someone changes the content of the textbox and then clicks on the button. Ideally, if the user clicks "yes" in the confirmation box, ...