Reputation: 229
How can I create an array of objects fromthe table excluding the header
How can I create object like this let list = [{name:'James',id='1'},{name:'Johnson',id:'2'}]
here is my javascript which wrote but the error here is it adds table header too and for select that is dropdown it does not add the selected value ? What changes should i make so that it should give desired output
const list = Array.from(document.querySelectorAll('table tr')).map(({
children
}) => ({
name: children[0].textContent,
id: children[1].textContent
}))
console.log(list)
<div>
<p id="size">2</p>
<table>
<tr>
<td>
<select name="plan" id="plan">
<option value="Cook">Cook</option>
<option value="James" selected>James</option>
<option value="professional">Professional</option>
<option value="corporate">Corporate</option>
</select>
</td>
<td>1</td>
</tr>
<tr>
<td>Johnson</td>
<td>2</td>
</tr>
</table>
</div>
Upvotes: 0
Views: 42
Reputation: 177885
const list = [...document.querySelectorAll('table tbody tr')].map(row => {
const name = row.cells[0].firstElementChild
return {
name: name ? name.value : row.cells[0].textContent,
id: row.cells[1].textContent
}
})
console.log(JSON.stringify(list))
<div>
<p id="size">2</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="plan" id="plan">
<option value="Cook">Cook</option>
<option value="James" selected>James</option>
<option value="professional">Professional</option>
<option value="corporate">Corporate</option>
</select>
</td>
<td>1</td>
</tr>
<tr>
<td>Johnson</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
Upvotes: 1