Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
}
]
like image 242
Ellone Avatar asked Nov 26 '25 10:11

Ellone


1 Answers

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)
like image 199
adeneo Avatar answered Nov 27 '25 22:11

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!