Alvin
Alvin

Reputation: 408

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);
                               }
                           });

Upvotes: 2

Views: 160

Answers (3)

Redu
Redu

Reputation: 26161

It's very simple to do these jobs with pure JS. Let's first create our test table as it should be and then obtain the desired array from the test table.

function tableMaker(o,h){
  var keys = Object.keys(o[0]),
  rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
                                                                  : "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
      rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
  return "<table>" + rows + "</table>";
}

var tableData = [{"Product ID": 1, "Product Name": "Adidas", Qty: 2, Price: 100, Delete: "<button>Delete</button>"},
                 {"Product ID": 2, "Product Name": "Nike", Qty: 1, Price: 50, Delete: "<button>Delete</button>"},
                 {"Product ID": 3, "Product Name": "Puma", Qty: 4, Price: 79, Delete: "<button>Delete</button>"},],
  ptContainer = document.getElementById("ptContainer"),
  productTable,
  productArray = [];
ptContainer.innerHTML = tableMaker(tableData,true);
productTable = document.getElementsByTagName("table")[0];
for (var i=1; i<productTable.rows.length; i++){
  productArray.push(productTable.rows[i].cells[0].textContent,
                    productTable.rows[i].cells[1].textContent,
                    productTable.rows[i].cells[2].textContent);
}
console.log(productArray);
<div id="ptContainer"></div>

Or you can even simplify the last part like;

for (var i=1; i<productTable.rows.length; i++){
  productArray.push(...[...productTable.rows[i].cells].slice(0,3).map(c => c.textContent));
}

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

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>

Upvotes: 1

Kenzo_Gilead
Kenzo_Gilead

Reputation: 2439

Try this one:

tableData.slice(0, 4);

You will store in tableData, only the first 4 cells...

Array.slice()

Upvotes: 0

Related Questions