Skip to content

Instantly share code, notes, and snippets.

@bennetthardwick
Created October 20, 2018 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bennetthardwick/f03e7d6489d559646b2b4ddb6c5fb03b to your computer and use it in GitHub Desktop.
Save bennetthardwick/f03e7d6489d559646b2b4ddb6c5fb03b to your computer and use it in GitHub Desktop.
Turn a table into a JSON and copy it!
(() => {
const table = document.querySelector('table');
const head = document.querySelector('thead');
const body = document.querySelector('tbody');
const keys = Array.from(head.querySelectorAll('th'))
.map(cell => cell.innerText);
const values = Array.from(body.querySelectorAll('tr'))
.map(row => Array.from(row.querySelectorAll('td')).map(cell => cell.innerText));
const data = values.map(row => row.reduce((acc, a, i) => ({
...acc,
[keys[i]]: a
}), {}));
clipboard(JSON.stringify(data, 0, 2));
function clipboard(s) {
const el = document.createElement('textarea');
el.value = s;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment