I am trying to build a Chrome extension (the intention is, this extension reads a badly coded and formatted table, generates a JSON and replaces the table with a cleaner, prettier table generated from the JSON). The table/script looks as follows (they are executable)
function arrayify(collection) {
return Array.prototype.slice.call(collection);
}
function factory(headings) {
return function(row) {
return arrayify(row.cells).reduce(function(prev, curr, i) {
prev[headings[i]] = curr.innerHTML ;
return prev;
}, {});
}
}
function parseTable(table) {
var headings = arrayify(table.tHead.rows[0].cells).map(function(heading) {
return heading.innerHTML ;
});
return arrayify(table.tBodies[0].rows).map(factory(headings));
}
var table = document.querySelector("table");
var data = parseTable(table);
console.log(data);
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<thead>
<th class="col-sm-2"></th>
<th class="col-sm-3"></th>
<th class="col-sm-1">Eats Grass</th>
<th class="col-sm-1">Eats Fish</th>
<th class="col-sm-1">Eats Meat</th>
<th class="col-sm-1">Drinks Wine</th>
</thead>
<tbody>
<tr>
<td class="td-dark" rowspan="2">Animal</td>
</tr>
<tr>
<td class="td-dark">Cow</td>
<td class="td-dark">
<input checked="checked" disabled="disabled" type="checkbox" />
</td>
<td class="td-dark"></td>
<td class="td-dark"></td>
<td class="td-dark"></td>
</tr>
<tr>
<td class="" rowspan="9">Mammal</td>
</tr>
<tr>
<td class="">Whale</td>
<td class="">
<input checked="checked" disabled="disabled" type="checkbox" />
</td>
<td class="">
<input checked="checked" disabled="disabled" type="checkbox" />
</td>
<td class=""></td>
<td class=""></td>
</tr>
<tr>
<td class="">Area 51 Alien</td>
<td class="">
<input checked="checked" disabled="disabled" type="checkbox" />
</td>
<td class="">
<input checked="checked" disabled="disabled" type="checkbox" />
</td>
<td class=""></td>
<td class="">
<input checked="checked" disabled="disabled" type="checkbox" />
</td>
</tr>
</tbody>
</table>
</body>
</html>
Problem is, as you see, the console JSON is not at all what I am hoping to get. What I do want is:
+-+
+-+
|
|
+------+Animal
| +
| |
| |
| |
| +----+ Cow
| +
| +-----+ Eats Grass
+-------+Mammal
+----+ Whale
| +
| |
| +---+ Eats Grass
| |
| +---+ Eats Fish
|
|
|
|
|
|
+-----+ Area 51 Alien
+
|
+-----+
|
+-----+
The table is huge with around a 100 columns and several sections
(like Animal
) with multiple, one or no subsections
(like Cow
, Whale
). How can this be done? I know the table is primitive, but changing it is impossible as it is beyond my control.
Edit: The table is malformed. This is the challenge! I cannot fix the table anyway. Therefore I am trying to write an addon to show it properly.
Longer example of table: http://pasted.co/5d779888