Skip to content

Instantly share code, notes, and snippets.

@Frondor Frondor/suckData.js
Last active Sep 27, 2018

Embed
What would you like to do?
HTML table data to JSON
/*
* THIS IS NOT A PLUGIN
* ~ but a personal snippet
*
* Sometimes when prototyping my designs, I like to get dummy data pretty fast.
* I use this snippet to extract that data from working (aka "real life") tables from other HTML tables I find on the net.
* So I'll need that same data but inside an object.
*
* This script assumes by default the table has the following structure:
* <table>
* <thead>
* <tr><th>
* <tbody>
* <tr><td>
*/
var o = { // default options
selectors: {
table: 'table',
th: 'thead th', // relative to $table
tr: 'tbody tr' // relative to $table
}
},
$table,
data = [],
headings = [],
log = console.log;
$table = document.querySelector(o.selectors.table);
// Get headings
$table.querySelectorAll(o.selectors.th).forEach((th) => {
headings[headings.length] = th.innerText;
});
$table.querySelectorAll(o.selectors.tr).forEach((tr, row) => {
var obj = data[row] = {};
tr.querySelectorAll('td').forEach((td, i) => {
obj[headings[i]] = td.innerText;
})
});
log(JSON.stringify(data));
@Rdhaliwal97

This comment has been minimized.

Copy link

commented Sep 27, 2018

my table will be generated on the fly so it won't have thead, th and tbody. is there any way out for me ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.