I'm trying to create a simple array with jquery from a table with only rows, but a row can contain multiple time elements.
I could only find solutions for tables with single td values and no children...
This is my table:
<div id="customhours">
<table>
<tbody>
<tr>
<td>Tuesday</td>
<td>
<time>17:00 - 18:00</time>
</td>
</tr>
<tr>
<td>Friday</td>
<td>
<time>16:00 - 17:00</time>
<time>17:00 - 18:00</time>
</td>
</tr>
</tbody>
</table>
</div>
The array I'm looking for is:
[["Tuesday", "17:00 - 18:00"], ["Friday", ["16:00 - 17:00, 17:00 - 18:00"]]]
Any help would be appreciated.
CodePudding user response:
For each row, find the day in the first <td>
and all the <time>
tags in the last <td>
:
let a = [] // Results will go here
$('#customhours tr').each(function() {
let day = $(this).find('td:first-child').text() // e.g. Tuesday
let times = []
$(this).find('td:last-child time').each(function(){
times.push($(this).text())
})
a.push([day, ( ( times.length == 1) ? times[0] : times )])
})
console.log(a)
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<div id="customhours">
<table>
<tbody>
<tr>
<td>Tuesday</td>
<td>
<time>17:00 - 18:00</time>
</td>
</tr>
<tr>
<td>Friday</td>
<td>
<time>16:00 - 17:00</time>
<time>17:00 - 18:00</time>
</td>
</tr>
</tbody>
</table>
</div>