Extracting this table into an array
$(function() {
var $table = $("#results"),
$headerCells = $table.find("thead th"),
$rowCells = $table.find("tbody tr td");
var headers = [],
rows = [],
combined = [];
$headerCells.each(function(k, v) {
headers[headers.length] = $(this).text();
});
$rowCells.each(function(k, v) {
rows[rows.length] = $(this).text();
});
console.log(headers);
console.log(rows);
console.log($headerCells.length);
console.log($rowCells.length);
for (var i = 0; i < $rowCells.length; i++) {
for (var j = 0; j < $headerCells.length; j++) {
combined.push([$($headerCells[j]).text(), $($rowCells[i]).text()]);
}
}
console.log(combined);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="results">
<thead>
<tr>
<th>User Name</th>
<th>User Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>fred nerk</td>
<td>Admin</td>
</tr>
<tr>
<td>Site Admin</td>
<td>Dude</td>
</tr>
<tr>
<td>User</td>
<td>slave</td>
</tr>
<tr>
<td>Admin</td>
<td>god</td>
</tr>
<tr>
<td>Specialist</td>
<td>thing</td>
</tr>
</tbody>
</table>
The number of headers is not known in advance
to help, headers gives me
["User Name", "User Job"]
rows gives me
["fred nerk", "Admin", "Site Admin", "Dude", "User", "slave", "Admin", "god", "Specialist", "thing"]
If I try and combine these arrays I get something like
["User Name", "fred nerk"] ["User Job", "fred nerk"] ["User Name", "Admin"] ["User Job", "Admin"] ["User Name", "Site Admin"] ["User Job", "Site Admin"] ["User Name", "Dude"] ["User Job", "Dude"] ["User Name", "User"] ["User Job", "User"] ["User Name", "slave"] ["User Job", "slave"] ["User Name", "Admin"] ["User Job", "Admin"] ["User Name", "god"] ["User Job", "god"] ["User Name", "Specialist"] ["User Job", "Specialist"] ["User Name", "thing"] ["User Job", "thing"]
As you can see this is not quite right and I need to do the array of arrays instead.. Something like
[{"User Name": "fred nerk","User Job", "Admin"}...]...
Can someone help? I'm not really a JS person, so this is an uphill challenge for me :)