Skip to content
Snippets Groups Projects
Commit 73a35d4e authored by susmitapiya's avatar susmitapiya
Browse files

function javascript file

parent 97588518
Branches
Tags
No related merge requests found
/**
* Make a table representation of the data
*
* @param {Array[Array[*]]} data The data to represent in the table, a 2D array
* @param {Array[String]} headerRowTexts The strings to show in the header row of the table.
* If null, no header row is created.
*/
function makeTable(data, headerRowTexts = null) {
let table = document.createElement('table');
let thead = document.createElement('thead');
table.append(thead);
// Construct the header row
if (headerRowTexts != null) { // Construct header row
let header = document.createElement('tr');
for(let s of headerRowTexts) {
let thElem = document.createElement('th');
thElem.textContent = s;
header.append(thElem);
}
thead.append(header);
}
// Construct the non-header rows
let tbody = document.createElement('tbody');
for (let row of data) {
let trElem = document.createElement('tr');
for (let value of row) {
let tdElem = document.createElement('td');
tdElem.textContent = value;
trElem.append(tdElem);
}
tbody.append(trElem);
}
table.append(tbody);
return table;
}
/**
* Make a table representation of the array of objects. Note: this function
* can generate an acceptable-looking output table only if the objects of
* objArr are simple enough. For instance, nested objects may lead to table
* cells with too much contents or to cells of the form [object Object] if
* string conversion methods have not been defined for those inner objects.
*
* @param {Array[Object]} objArr
*/
function objectsAsTable(objArr) {
if (objArr.length == 0) {
return makeTable([], null);
}
firstObj = objArr[0];
let header = Object.keys(firstObj);
let arr = objArr.map(e => Object.values(e));
return makeTable(arr, header);
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment