Skip to content

Add functionality for easily creating table with headers #109

@marklagendijk

Description

@marklagendijk

Currently creating a table with headers requires quite some effort.
However, it should be relatively easy to provide this functionality in the library.
At the very least some better examples could be supplied.

Here is a rather simplistic approach that works quite well:

const { table } = require('table');
const chalk  = require('chalk');

function printTable(data, options) {
    if (!data || !data.length) {
        return;
    }
    options = options || {};
    options.columns = options.columns ||  Object.keys(data[0]);
    options.headerStyleFn = options.headerStyleFn || chalk.bold;
    const header = options.columns.map(property => options.headerStyleFn(property));
    const tableText = table([
        header,
        ...data.map(item => options.columns.map(property => item[property]))
    ]);
    console.log(tableText);
}

const data = [
    { firstName: 'John', lastName: 'Doe' }
];

printTable(data);

printTable(data ,{
        columns: ['lastName', 'firstName']
    }
);

printTable(data, {
    headerStyleFn: chalk.red
});

printTable(data, {
    headerStyleFn: header => chalk.bold(chalk.red(header))
});

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions