I am looking to generate tables with data derived from arrays. Each table will have its own array of data and I also have an array that contains the names of the table data arrays along with some additional values.
It seems like the issue lies in table(x[1],sub)
because x[1]
is not being treated as a variable name, but rather its value is acting as a string.
In PHP, you could use something like $$x[1]
, but how can this be achieved in JavaScript?
var xxx = [[ 'Adam' , 'table1' ],
[ 'Ben' , 'table2' ],
[ 'Charlie' , 'table3' ]];
// arrays for table data
var table1 = [[ 'a' , '1' ],
[ 'b' , '2' ],
[ 'c' , '3' ],
[ 'd' , '4' ],
[ 'e' , '5' ]];
var table2 = [[ 'a' , '1' ],
[ 'b' , '2' ],
[ 'c' , '3' ],
[ 'd' , '4' ],
[ 'e' , '5' ]];
var table3 = [[ 'a' , '1' ],
[ 'b' , '2' ],
[ 'c' , '3' ],
[ 'd' , '4' ]],
// function to create table
function table(tableData,sub) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
sub ? sub.appendChild(table) : document.body.appendChild(table);
}
// apply everything to HTML
xxx.forEach( x => {
var con = document.querySelector('#content');
var sub = document.createElement('div');
con.appendChild(sub);
var h = document.createElement('h3');
h.innerHTML = x[0];
sub.appendChild(h3);
table(x[1],sub); // x[1] presents an issue
});
<div id="myID">
<h2>Headline</h2>
<div id="content">
</div>
</div>