Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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));
}
Owner

WickyNilliams commented Feb 27, 2014

Can be improved quite a bit by adding type hinting to each column, so you get the correct types back:

<th data-type="int">age</th>

Though you could brute force this by calling JSON.parse(cellValue), but may not give desired results.

Could also add programmatic rules for processing titles to friendlier names, or again use data attributes:

<th data-name="eyeColor">eye color</th>

Hey, I'm interested in your code but I have a question:
Currently I'm working on a chrome extension and I need to parse a table to array for future process. In the table I don't have part. So how to I process this type of table.

http://codepaste.net/joh9i4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment