/**
* Генерация html таблицы
* @param headers Array
* @param rows Array
* @param attr Object Table attributes
* @return string
*/
function generateTable(rows, headers = [], attr = {}) {
var attributes = [];
Object.keys(attr).forEach(function (key) {
attributes.push(key + '="' + attr[key] + '"');
});
var table = '<table ' + attributes.join(' ') + '>';
// Headers
table += '<thead>';
headers.forEach(function(header) {
table += '<tr>';
if (Array.isArray(header)) {
header.forEach(function (col) {
if (typeof col === 'object') {
var attributes = [];
var attr = col.attr;
if (Object.keys(attr).length) {
Object.keys(attr).forEach(function(key){
attributes.push(key + '="' + attr[key] + '"');
});
}
table += '<td ' + attributes.join(' ') + '><b>' + col.value.replace(/\"/g, '"') + '</b></td>';
} else if (typeof col === 'string') {
table += '<td><b>' + col.replace(/\"/g, '"') + '</b></td>';
} else {
console.warn('col not string|object!', col);
}
});
} else if (typeof header === 'object') {
table += '<td><b>' + header.value.replace(/\"/g, '"') + '</b></td>';
} else if (typeof header === 'string') {
table += '<td><b>' + header.replace(/\"/g, '"') + '</b></td>';
} else {
console.warn('col is not a (string|object)!', col);
}
table += '</tr>';
});
table += '</thead>';
// Rows
table += '<tbody>';
rows.forEach(function(row) {
table += '<tr>';
if (Array.isArray(row)) {
row.forEach(function (col) {
if (typeof col === 'object') {
var attributes = [];
var attr = col.attr;
if (Object.keys(attr).length) {
Object.keys(attr).forEach(function(key){
attributes.push(key + '="' + attr[key] + '"');
});
}
table += '<td ' + attributes.join(' ') + '>' + col.value.replace(/\"/g, '"') + '</td>';
} else if (typeof col === 'string') {
table += '<td>' + col.replace(/\"/g, '"') + '</td>';
} else {
console.warn('col not a (string|object)!', col);
}
});
} else if (typeof row === 'string') {
table += '<td>' + row.replace(/\"/g, '"') + '</td>';
} else {
console.warn('row is not string|object!', col);
}
table += '</tr>';
});
table += '</tbody>';
table += '</table>';
return table;
}