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">
<meta charset="UTF-8">
<th>eye colour</th>
<script src="parseTable.js"></script>
var table = document.querySelector("table");
var data = parseTable(table);
// [
// {
// "name" : "dave",
// "age" : "35",
// "eye colour" : "blue"
// }, {
// "name" : "sarah",
// "age" : "29",
// "eye colour" : "brown"
// }, {
// "name" : "john",
// "age" : "42",
// "eye colour" : "green"
// },
// ]
* converts array-like object to array
* @param collection the object to be converted
* @return {Array} the converted object
function arrayify(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));

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.

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