Skip to content Skip to sidebar Skip to footer

Put Table In Array

Hey guy's I have a table

Solution 1:

You need nested loops to achieve the required result. See the below snippet

 var params = {
        "fruit":"apple",
        "test": "Nope",
        "values": [
       
        ],
    }
    
    $(function(){
        $('button').click(function() {
            $("#mytable tr").each(function(index, item){
              var temp = []
              if(index == 0) {
                $(item).find('th').each(function(idx, col){
                    temp.push($(col).text());
                })
              }
              $(item).find('td').each(function(idx, col){
                temp.push($(col).text());
              })
              params.values.push(temp)
            })
             console.log(params);
        })
      
    })
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>
<button>Click</button>

Solution 2:

You can use each() loop in combination with map() and get() to add to each table row as new array to params.values.

var params = {
  "fruit": "apple",
  "test": "Nope",
  "values": [],
}

$('table tr').each(function() {
  params.values.push($(this).find('*').map(function() {
    return $(this).text()
  }).get())
});

console.log(params)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

You can also instead of each() loop and push() just use map() and get() two times.

var params = {
  "fruit": "apple",
  "test": "Nope"
}

params.values = $('table tr').map(function() {
  return [$(this).find('*').map(function() {
    return $(this).text()
  }).get()]
}).get();

console.log(params)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Post a Comment for "Put Table In Array"

Firstname Lastname Age