Table To Object
by mesak
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</tbody>
</table>
</body>
</html>
JavaScript
let headData = []
for(let trNode of document.querySelectorAll('thead >tr') ){
headData = Array.from(trNode.querySelectorAll('th')).map((n=>n.innerText))
console.log('headData', headData )
}
let bodyData = []
for(let trNode of document.querySelectorAll('tbody > tr') ){
let rowData = Array.from(trNode.querySelectorAll('td')).map((n=>n.innerText))
console.log('rowData', rowData )
bodyData.push( Array.from(headData.entries()).reduce((data,[index,value])=>{
data[value] = rowData[index]
return data
},{}))
}
//==== ↑↑↑↑↑ version 1 ↑↑↑↑↑ ====
HTMLTableRowElement.prototype.toArray = function(){
return [...this.cells].map(cell => cell.innerText);
}
HTMLTableElement.prototype.toArray = function(){
return [...this.rows].map((row=>row.toArray()))
}
console.log( 'bodyData ',bodyData )
console.log( 'objectify = ',document.querySelector('table').toArray() )
for(let trNode of document.querySelectorAll('tbody > tr') ){
let rowData = trNode.toArray()
console.log('rowData', rowData )
bodyData.push( Array.from(headData.entries()).reduce((data,[index,value])=>{
data[value] = rowData[index]
return data
},{}))
}
//==== ↑↑↑↑↑ version 2 ↑↑↑↑↑ ====
let bodyObject = [...document.querySelectorAll('tbody > tr')].map(trNode => {
let rowData = trNode.toArray();
return headData.reduce((data, value, index) => ({...data, [value]: rowData[index]}),{});
});
console.log( 'bodyObject ',bodyObject )
//==== ↑↑↑↑↑ version 3 from ChatGPT ↑↑↑↑↑ ====