Ellone Ellone - 27 days ago 9
Javascript Question

Convert HTML table (as a string) into JS Objects array

What's a simple/elegant way to convert a string containing the source code of a HTML table into an array of javascript object ?

It would convert each

<tr>
into an object and each
<td>
into an object property.

The properties names aren't extracted from the table, they are already defined.

For example, passing this code as a string to the javascript function :

<table>
<tr>
<td>2280</td>
<td>23020044623</td>
<td>RTS</td>
<td>EUR</td>
<td>1</td>
<td>29/07/2015</td>
<td>10/07/2017</td>
<td>no</td>
</tr>
<tr>
<td>2281</td>
<td>23020011223</td>
<td></td>
<td>GBP</td>
<td>0,78</td>
<td>10/10/2013</td>
<td>10/10/2018</td>
<td>Occult</td>
</tr>
</table>


would return :

// Properties names are known
[
{
prop1: '2280',
prop2: '23020044623',
prop3: 'RTS',
prop4: 'EUR',
prop5: '1',
prop6: '29/07/2015',
prop7: '10/07/2017',
prop8: 'no'
},
{
prop1: '2281',
prop2: '23020011223',
prop3: '',
prop4: 'GBP',
prop5: '0,78',
prop6: '10/10/2013',
prop7: '10/10/2018',
prop8: 'Occult'
}
]

Answer

You could parse the HTML and use map and reduce to return the expected array of objects

var html   = '<table><tr><td>2280</td><td>23020044623</td><td>RTS</td><td>EUR</td><td>1</td><td>29/07/2015</td><td>10/07/2017</td><td>no</td></tr><tr><td>2281</td><td>23020011223</td><td></td><td>GBP</td><td>0,78</td><td>10/10/2013</td><td>10/10/2018</td><td>Occult</td></tr></table>';
var parser = new DOMParser();
var doc    = parser.parseFromString(html, "text/html");
var obj    = [].map.call(doc.querySelectorAll('tr'), tr => {
    return [].slice.call(tr.querySelectorAll('td')).reduce( (a,b,i) => {
        return a['prop' + (i+1)] = b.textContent, a;
    }, {});
});

console.log(obj)