stringTable.js
A groundbreaking, innovative JavaScript library to do something that's literally never been attempted before: formatting an array of data objects as a textual table.
Installation
npm install string-table
Example
var users = [
{ name: 'Dan', gender: 'M', age: 29 },
{ name: 'Adam', gender: 'M', age: 31 },
{ name: 'Lauren', gender: 'F', age: 33 }
];
stringTable.create(users);
It works with multi-line strings, too!
# This example is in CoffeeScript for readability.
books = [
{
title: 'The Cat in the Hat',
opening:
"""
The sun did not shine.
It was too wet to play.
So we sat in the house
All that cold, cold, wet day.
"""
},
{
title: 'Green Eggs and Ham',
opening:
"""
I am Sam.
Sam I am.
Do you like green eggs and ham?
"""
}
]
stringTable.create(books)
#
# Result:
#
# | title | opening |
# --------------------------------------------------------
# | The Cat in the Hat | The sun did not shine. |
# | | It was too wet to play. |
# | | So we sat in the house |
# | | All that cold, cold, wet day. |
# | Green Eggs and Ham | I am Sam. |
# | | Sam I am. |
# | | Do you like green eggs and ham? |
#
You can also specify options to customize how the table is formatted:
var table = stringTable.create(users, options);
The available options are summarized below.
Options
An array of strings indicating which column headers to include (and in what order)
Default: every property from the first object in the list
Example
stringTable.create(users, { headers: ['age', 'name'] });
Whether or not to capitalize the table's column headers
Default: false
Example
stringTable.create(users, { capitalizeHeaders: true });
formatters
An object mapping column names to formatter functions, which will accept (value, header)
arguments
Default: none
Example
stringTable.create(users, {
formatters: {
name: function(value, header) { return value.toUpperCase(); }
}
});
A formatter may also return an object with the properties { value, format }
, where format
in turn can have the properties { color, alignment }
.
stringTable.create(users, {
formatters: {
gender: function(value, header) {
return {
value: value,
format: {
color: value === 'M' ? 'cyan' : 'magenta',
alignment: 'right'
}
};
}
}
});
typeFormatters
An object mapping data types ('string'
, 'number'
, 'boolean'
, etc.) to formatter functions (has lower precedence than formatters
option)
Default: none
Example
stringTable.create(users, {
typeFormatters: {
number: function(value, header) { return value.toFixed(2); }
}
});
outerBorder
and innerBorder
The character(s) used to enclose the table and to delimit cells within the table, respectively
Defaults: '|'
for both
Example
stringTable.create(users, {
outerBorder: '%',
innerBorder: '$'
});
rowSeparator
The character used to separate rows in the table
Default: none
Example
stringTable.create(users, { rowSeparator: '~' });
The character used to separate the header row from the table body
Default: '-'
Example
stringTable.create(users, { headerSeparator: '*' });