user3562751
user3562751

Reputation: 263

Put all rows in a table into an array of arrays in jquery

I have a table like so for Outbound usage of Pharmacies

Pharmacy Name | Pharmacy ID | Call | SMS | Email | P | Total
------------------------------------------------------------
Test 1        | 123456      |  1   | 2   |  3    | 4 |  10
------------------------------------------------------------
Test 2        | 123457      |  1   | 2   |  3    | 4 |  10
-----------------------------------------------------------

I am trying to export this table to an excel sheet. How would I go about this when clicking a button and passing this data to my controller?

So far I have

$("tr").each(function () {

     alert( $("td").text());
});

But it is giving me all the tds.

I would like to be able to store the values of each row into an object.

Upvotes: 0

Views: 101

Answers (2)

Evil Buck
Evil Buck

Reputation: 1068

I think what you're looking for is:

$('tr').map(function(i, tr) {
  return $(tr).find('td').map(function(j, td) {
    return $(td).text();
  });
});

EDIT: how weird. Jquery seems to flatten them.

var parentArr = [];
$('tr').each(function() {
  var children = [];
  $(this).find('td').each(function(){
    children.push($(this).text());
  });
  parentArr.push(children);
});

this could definitely be solved a little more elegantly using ecmascript 5 or underscore/lodash methods.

Upvotes: 1

user3562751
user3562751

Reputation: 263

Here is what I have so far

    var items;
    var data = [];

    $('tr').map(function (i, tr) {
        items = [];
        return $(tr).find('td').map(function (j, td) {

            items[j] = $(td).text();
            data[i].push(items[j]);
            return $(td).text();
        });

        alert(data);
    });

Upvotes: 0

Related Questions