How can below console.log output be formatted? Name column can be of different length so columns are not aligned correctly. Example:-
3 Answers
use \t for real tab in the output.
console.log('name1\t14')
console.log('name2nam2\t12')
console.log('name3Nam3Nam\t13')
console.log('name1\t123421')
console.log('name1\t912421')
but probably what you want are console.table MDN
Comments
If you don't have access to console.table() (which is unavailable in some contexts, like Google App Scripts logging), you can use string.padEnd() to make all your strings the same length. It takes two arguments: the desired length, and the character to pad the string with. This will give you table-like formatting.
Example where we want the first column to be 28 characters wide:
var keys = someObject.getKeys();
var log = "";
keys.forEach(key => {
log += `${key.padEnd(28, ' ')}: \t${props.getProperty(key)}\n`;
});
console.log(log);
Output something like this:
previousRevisedWordCount : 47690.0
previousPercent : 0.4531134139945382
previousUnrevisedFileCount : 59.0
previousUnrevisedWordCount : 62924.0
previousDay : Fri Feb 16 18:18:38 GMT-06:00 2024
previousRevisedFileCount : 36.0
If you're iterating through a bunch of strings and you don't know the length, you could find the longest one first, then call string.padEnd(n + 1, " "), where n is the length of the longest string.
