I would like to take a table and convert it to an array of arrays. In other words, the table would be my overarching array, and each row would be an array within that array. Is there a way to do this with the table text? I'm also interested in ensuring that strings remain as strings, but integers are converted to the int type.
I've tried multiple methods of looping through the table and printing to the console, but I haven't found a way to output the rows as arrays within the table's array, with the strings remaining as string type and the integers being parsed to int type.
I got to this point, but I'm unclear on how to do this with the DOM elements:
function displayConsole() {
console.log(myTableArray);
trName = document.querySelectorAll(".table tbody, tr");
console.log(trName);
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName('td');
var trArray = [];
tdLength = td.length;
for (i = 0; i < tdLength; i ) {
trArray.push( td[i].innerText );
}
console.log(trArray);
This is my first step of the process, after which I also hope to pass the array of arrays as an object to Django forms and reuse it on other pages.
CodePudding user response:
You need nested loops to create nested arrays. You can use map()
for each level.
You can use a regular expression to test if the table cell looks like an integer, and call parseInt()
to convert it.
function displayConsole() {
const trs = document.querySelectorAll(".table tbody tr");
var trArray = Array.from(trs).map(tr => Array.from(tr.cells).map(td => {
if (/^-?\d $/.test(td.innerText)) {
return parseInt(td.innerText);
} else {
return td.innerText;
}
}));
console.log(trArray);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>