Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active December 20, 2022 09:53
Show Gist options
  • Save wojtekmaj/c6e4a0f359f0083f22532057169253ed to your computer and use it in GitHub Desktop.
Save wojtekmaj/c6e4a0f359f0083f22532057169253ed to your computer and use it in GitHub Desktop.
Transform HTML table into JSON data.
/**
* Transforms HTML table into JSON data.
*
* Sample input:
*
* <table>
* <thead>
* <tr>
* <th>Heading 1</th>
* <th>Heading 2</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>Value 1a</td>
* <td>Value 2a</td>
* </tr>
* <tr>
* <td>Value 1b</td>
* <td>Value 2b</td>
* </tr>
* </tbody>
* </table>
*
* Sample output:
*
* [
* { 'Heading 1': 'Value 1a', 'Heading 2': 'Value 2a' },
* { 'Heading 1': 'Value 1b', 'Heading 2': 'Value 2b' }
* ]
*
* @param {HTMLTableElement} table
*/
function tableToJSON(table) {
const headers = Array.from(table.querySelectorAll('thead tr th')).map(el => el.textContent.trim());
const result = [];
const rows = Array.from(table.querySelectorAll('tbody tr'));
rows.forEach(row => {
const cells = Array.from(row.querySelectorAll('td')).map(el => el.textContent.trim());
result.push(headers.reduce((rowRes, header, headerIndex) => {
return {
...rowRes,
[header]: cells[headerIndex]
};
}, {}));
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment