There is a message recieved from the backend which looks like this:
[
{
"Name": "ABC",
"ColumnType": "NUMBER"
},
{
"Name": "XYZ",
"ColumnType": "STRING"
},
{
"Name": "EFG",
"ColumnType": "NUMBER"
},
{
"Name": "JKL",
"ColumnType": "STRING"
},
{
"Name": "TOP",
"ColumnType": "TIMESTAMP"
},
]
The "Name" is used as the column name in the table and the data in the column is aligned w.r.t the column type i.e For a ColumnType "NUMBER" and "TIMESTAMP" right align and for ColmnType "STRING" left align.
I have tried the following,
var td = document.getElementsByTagName('td');
let tdArr = Array.from(td);
for (var item in snapshot) {
let DataHeader = snapshot[item].DataHeader;
for(let x in DataHeader){
let colType = snapshot[item].DataHeader[x].columnType;
for(let z in tdArr){
if(colType === 'STRING' && colType !== 'NUMBER'){
tdArr[z].style.textAlign= "left";
}
else if(colType === 'NUMBER' && colType !== 'STRING'){
tdArr[z].style.textAlign= "right";
}
else if(colType === 'TIMESTAMP'){
tdArr[z].style.textAlign= "right";
}
}
}
}
This however sets all tds to either right align or left align. How do I work around this? I know I'm setting all td elements and I'm not sure how I can grab td elements of a particular column.
The above shown message is part of a snapshot object which has a DataHeader. The DataHeader contains the "Name" and the "ColumnType".
When using .forEach() or .map() you get the index as second parameter, which can be very helpful
let columnInfos = [
{
"Name": "ABC",
"ColumnType": "NUMBER"
},
{
"Name": "XYZ",
"ColumnType": "STRING"
},
{
"Name": "EFG",
"ColumnType": "NUMBER"
}
]
columnInfos.forEach((columnInfo, index) => {
let columnType = columnInfo.ColumnType
let tds = Array.from(document.querySelectorAll(`td:nth-of-type(${index+1})`))
if(columnType === 'NUMBER' || columnType === 'TIMESTAMP') {
tds.forEach(td => td.style.textAlign = 'right')
}else if(columnType === 'STRING'){
tds.forEach(td => td.style.textAlign = 'right')
}
})