Alvin Alvin - 3 months ago 12
jQuery Question

Specific table cells into array

I have a table below that consist of a product. However, I only want to insert the first 4 cells of the each row as an Array. So the array would be

[1, Adidas, 2 , $100, 2, Nike, 1 , $50]


Product ID | Product Name | Qty | Price |
1 | Adidas | 2 | $100 | Delete btn
2 | Nike | 1 | $50 | Delete btn


I tried and got out this jquery code, however, it insert all of the td of each row into the array, which is not what I want.

How do I modify this set of code to only insert first 4 and exclude the last cell? Thank you.

$("#checkoutList > tbody > tr").each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});

Answer

Use jQuery each() and map() method to genearate the array. To exclude last column use combination of :not() and :last-child pseudo-class selector.

// array for result
var res = [];
// iterate over the tr
$("table > tbody > tr").each(function() {
  // push the content array to `res`
  res.push(
     // get all td except last and generate content array
     $('td:not(:last-child)', this).map(function() {
        // get content and trim
        return $(this).text().trim();
        // get the result as an array
     }).get()
  );
});

var res = [];

$("table > tbody > tr").each(function() {
  res.push($('td:not(:last-child)', this).map(function() {
    return $(this).text().trim();
  }).get());
});

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>
        Product ID</td>
      <td>Product Name</td>
      <td>Qty</td>
      <td>Price</td>
      <td>Price</td>
  </thead>
  <tbody>
    <tr>
      <td>
        1</td>
      <td>Adidas</td>
      <td>2</td>
      <td>$100</td>
      <td>Delete btn</td>
    </tr>
    <tr>
      <td>
        2</td>
      <td>Nike</td>
      <td>1</td>
      <td>$50</td>
      <td>Delete btn</td>
    </tr>
  </tbody>
</table>

Comments