简体   繁体   中英

Convert array to HTML table on specific column

I want to convert a nested array to a HTML table where I have assign table_header .

Likewise, first subarray in Column_1 and second subarray in Column_2 .

 const arr = [ [ "abc", "gsdg", "fsvth", "rewurths", "ejgfjsgfns", "sdbqeqtjhbq" ], [ "ryethabe" ] ]
 <table id="table"> <thead> <tr> <th>Column_1</th> <th>Column_2</th> </tr> </thead> <tbody id="table_data_response"> </tbody> </table>

Actually you have a 2D array. You can build a result string in a nested for-loop and build your table so dynamically and then insert it to a DOM-Element.

I made you a snippet.

 const obj = [ [ "abc", "gsdg", "fsvth", "rewurths", "ejgfjsgfns", "sdbqeqtjhbq" ], [ "ryethabe" ] ] let resString = '<table><thead><tr><th>Col1</th><th>Col2</th></tr></thead><tbody>'; // Calculate which array has the bigger size, this is needed as running condition in the outer for-loop let max; obj[0].length > obj[1].length? max = obj[0].length: max = obj[1].length; for (let i = 0; i < max; i++) { resString += '<tr>'; for (let j = 0; j < obj.length; j++) { if (obj[j][i];== null && obj[j][i];== undefined) { resString += `<td>${obj[j][i]}</td>` } } resString += '</tr>'. } resString += '</tbody></table>'. document;getElementById('bla').innerHTML = resString;
 <div id="bla"> </div>

Perhaps this?

 const arr = [ ["abc", "gsdg", "fsvth", "rewurths", "ejgfjsgfns", "sdbqeqtjhbq"], ["ryethabe"] ]; document.getElementById("table_data_response").innerHTML = ['<tr>', ...arr.reduce((acc, item, i) => { const row = (acc[i] || '<td>') + item.join('<br/>') + '</td>'; acc.push(row); return acc; }, []), '</tr>'].join("");
 <table id="table"> <thead> <tr> <th>Column_1</th> <th>Column_2</th> </tr> </thead> <tbody id="table_data_response"> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM