Skip to content

Instantly share code, notes, and snippets.

@fassetar
Forked from WickyNilliams/index.html
Created December 12, 2017 16:12
Show Gist options
  • Save fassetar/72a4bbc5ee46054fe6020863c1d73bc9 to your computer and use it in GitHub Desktop.
Save fassetar/72a4bbc5ee46054fe6020863c1d73bc9 to your computer and use it in GitHub Desktop.
parseTable.js - convert HTML table to array of objects
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>parseTable</title>
</head>
<body>
<table>
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>eye colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>dave</td>
<td>35</td>
<td>blue</td>
</tr>
<tr>
<td>sarah</td>
<td>29</td>
<td>brown</td>
</tr>
<tr>
<td>john</td>
<td>42</td>
<td>green</td>
</tr>
</tbody>
</table>
<script src="parseTable.js"></script>
<script>
var table = document.querySelector("table");
var data = parseTable(table);
console.log(data);
// [
// {
// "name" : "dave",
// "age" : "35",
// "eye colour" : "blue"
// }, {
// "name" : "sarah",
// "age" : "29",
// "eye colour" : "brown"
// }, {
// "name" : "john",
// "age" : "42",
// "eye colour" : "green"
// },
// ]
</script>
</body>
</html>
/**
* converts array-like object to array
* @param collection the object to be converted
* @return {Array} the converted object
*/
function arrayify(collection) {
return Array.prototype.slice.call(collection);
}
/**
* generates factory functions to convert table rows to objects,
* based on the titles in the table's <thead>
* @param {Array[String]} headings the values of the table's <thead>
* @return {Function} a function that takes a table row and spits out an object
*/
function factory(headings) {
return function(row) {
return arrayify(row.cells).reduce(function(prev, curr, i) {
prev[headings[i]] = curr.innerText;
return prev;
}, {});
}
}
/**
* given a table, generate an array of objects.
* each object corresponds to a row in the table.
* each object's key/value pairs correspond to a column's heading and the row's value for that column
*
* @param {HTMLTableElement} table the table to convert
* @return {Array[Object]} array of objects representing each row in the table
*/
function parseTable(table) {
var headings = arrayify(table.tHead.rows[0].cells).map(function(heading) {
return heading.innerText;
});
return arrayify(table.tBodies[0].rows).map(factory(headings));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment