Format an array of data objects as a textual table.

Overview

st2

build check-code-coverage npm npm (scoped)

st2 is string-table refactored in TypeScirpt with more enhancements:

  • add type information, then it can be used in modern IDE like vscode to work with IntelliSense.
  • return an empty string for null, undefined, '', {}, [] and [{}] by default.
  • accept a single object input, ie, treat it as an array including only one element.
  • support object properties.
  • filter out "empty" items (null, undefined, {} and '') in the input array automatically.
  • rewrite all tests in TypeScirpt, using ava and c8.

Installation

npm install @dteam/st2

Example

import {createTable} from '@dteam/st2';

const users = [
  {name: 'Dan', gender: 'M', age: 29},
  {name: 'Adam', gender: 'M', age: 31},
  {name: 'Lauren', gender: 'F', age: 33},
];

createTable(users);

/*
 * Result:
 *
 * | name   | gender | age |
 * -------------------------
 * | Dan    | M      |  29 |
 * | Adam   | M      |  31 |
 * | Lauren | F      |  33 |
 */

For the input of createTable, please note:

  • a single object will be treat as [object].
  • null, undefined, '', {}, [] and [{}] will return an empty string.
  • "empty" items in the input will be removed, fox examples:
createTable([null, undefined, '', {}, {foo: 3, bar: 4}]);

/*
 * Result:
 *
 * | foo | bar |
 * -------------
 * |   3 |   4 |
 */

Please check the test files for all usage examples.

Options

You can also specify options to customize how the table is formatted:

const table = createTable(users, options);

The available options are summarized below.

headers

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

createTable(users, {headers: ['age', 'name']});

/*
 * Result:
 *
 * | age | name   |
 * ----------------
 * |  29 | Dan    |
 * |  31 | Adam   |
 * |  33 | Lauren |
 */

capitalizeHeaders

Whether or not to capitalize the table's column headers

Default: false

Example

createTable(users, {capitalizeHeaders: true});

/*
 * Result:
 *
 * | Name   | Gender | Age |
 * -------------------------
 * | Dan    | M      |  29 |
 * | Adam   | M      |  31 |
 * | Lauren | F      |  33 |
 */

formatters

An object mapping column names to formatter functions, which will accept (value, header) arguments

Default: none

Example

createTable(users, {
  formatters: {
    name: function (value, header) {
      return value.toUpperCase();
    },
  },
});

/*
 * Result:
 *
 * | name   | gender | age |
 * -------------------------
 * | DAN    | M      |  29 |
 * | ADAM   | M      |  31 |
 * | LAUREN | F      |  33 |
 */

A formatter may also return an object with the properties { value, format }, where format in turn can have the properties { color, alignment }.

NOTE: color output required colors package:

npm i colors

More details can be found in: https://www.npmjs.com/package/colors#colors-and-styles

// don't forget to import colors
include 'colors';

createTable(users, {
  formatters: {
    gender: function (value, header) {
      return {
        value: value,
        format: {
          // All supported colors and styles can be found in official doc: https://www.npmjs.com/package/colors
          color: value === 'M' ? 'cyan' : 'magenta',
          alignment: 'right',
        },
      };
    },
  },
});

/*
 * Result:
 *
 * | name   | gender |    age |
 * ----------------------------
 * | Dan    |      M |  29.00 |
 * | Adam   |      M |  31.00 |
 * | Lauren |      F |  33.00 |
 *
 * (Imagine the Ms are cyan and the F is magenta above.)
 */

For internal objects properties, you can use formatters too.

const numbers = [
  {outValue: 1, insideValue: {a: 1, b: 'a1'}},
  {outValue: 2, insideValue: {a: 2, b: 'a2'}},
  {outValue: 3, insideValue: {a: 3, b: 'a3'}},
];

createTable(numbers, {
  formatters: {
    insideValue: {
      a: (value: number) => value.toFixed(2),
      b: (value: string) => value.toUpperCase(),
    },
  },
  rowSeparator: '-',
});

/*
 * Result:
 *
 * | outValue | insideValue   |
 * ----------------------------
 * |        1 | | a    | b  | |
 * |          | ------------- |
 * |          | | 1.00 | A1 | |
 * ----------------------------
 * |        2 | | a    | b  | |
 * |          | ------------- |
 * |          | | 2.00 | A2 | |
 * ----------------------------
 * |        3 | | a    | b  | |
 * |          | ------------- |
 * |          | | 3.00 | A3 | |
 *
 */

typeFormatters

An object mapping data types ('string', 'number', 'boolean', etc.) to formatter functions (has lower precedence than formatters option)

Default: none

Example

createTable(users, {
  typeFormatters: {
    number: function (value, header) {
      return value.toFixed(2);
    },
  },
});

/*
 * Result:
 *
 * | name   | gender |    age |
 * ----------------------------
 * | Dan    | M      |  29.00 |
 * | Adam   | M      |  31.00 |
 * | Lauren | F      |  33.00 |
 */

A type formatters will also be applied for the values in the internal objects with the same type.

const numbers = [
  {outValue: 1, insideValue: {value: 1}},
  {outValue: 2, insideValue: {value: 2}},
  {outValue: 3, insideValue: {value: 3}},
];

createTable(numbers, {
  typeFormatters: {
    number: (value: number) => value.toFixed(2),
  },
  rowSeparator: '-',
});

/*
 * Result:
 *
 * | outValue | insideValue |
 * --------------------------
 * | 1.00     | | value |   |
 * |          | ---------   |
 * |          | | 1.00  |   |
 * --------------------------
 * | 2.00     | | value |   |
 * |          | ---------   |
 * |          | | 2.00  |   |
 * --------------------------
 * | 3.00     | | value |   |
 * |          | ---------   |
 * |          | | 3.00  |   |
 */

outerBorder and innerBorder

The character(s) used to enclose the table and to delimit cells within the table, respectively

Defaults: '|' for both

Example

createTable(users, {
  outerBorder: '%',
  innerBorder: '$',
});

/*
 * Result:
 *
 * % name   $ gender $ age %
 * -------------------------
 * % Dan    $ M      $  29 %
 * % Adam   $ M      $  31 %
 * % Lauren $ F      $  33 %
 */

rowSeparator

The character used to separate rows in the table

Default: none

Example

createTable(users, {rowSeparator: '~'});

/*
 * Result:
 *
 * | name   | gender | age |
 * -------------------------
 * | Dan    | M      |  29 |
 * ~~~~~~~~~~~~~~~~~~~~~~~~~
 * | Adam   | M      |  31 |
 * ~~~~~~~~~~~~~~~~~~~~~~~~~
 * | Lauren | F      |  33 |
 */

headerSeparator

The character used to separate the header row from the table body

Default: '-'

Example

createTable(users, {headerSeparator: '*'});

/*
 * Result:
 *
 * | name   | gender | age |
 * *************************
 * | Dan    | M      |  29 |
 * | Adam   | M      |  31 |
 * | Lauren | F      |  33 |
 */

Again, the test files shows all examples with different options.

How to deploy

  1. npm login
  2. npm run build
  3. npm publish

Note: if you changed registry in your ~/.npmrc, you need to comment it out before deployment.

Thanks

Finally, we want to thank string-table for providing a great way to show a list of structure data in cli. Without it, st2 will not happen.

You might also like...

Portable Activity Timeline that draws the Timeline based on data given in JSON or CSV format

Portable Activity Timeline that draws the Timeline based on data given in JSON or CSV format

Portable Activity Timeline that draws the Timeline based on data given in JSON or CSV format. By clicking on any activity a detailed modal window is displayed. Initially developed for post incident investigations to get a overview of the situation in an it-environment.

Oct 11, 2022

A Leaderscore app that send data to an API created from Postman and allow users to save names and scores in a table. Built with JavaScript

A Leaderscore app that send data to an API created from Postman and allow users to save names and scores in a table. Built with JavaScript

Leaderboard The leaderboard website displays scores submitted by different players. It also allows you to submit your score. All data is preserved tha

May 16, 2022

A regular table library, for async and virtual data models.

A regular table library, for async and virtual data models.

A Javascript library for the browser, regular-table exports a custom element named regular-table, which renders a regular HTML table to a sticky p

Dec 16, 2022

Simple modern JavaScript ES6 library that fetches JSON data into an HTML table which displays nicely within a Bootstrap 4 Card.

Simple modern JavaScript ES6 library that fetches JSON data into an HTML table which displays nicely within a Bootstrap 4 Card. Uses simplenotsimpler/modern-table library.

Feb 17, 2022

Fundamentos, estruturas, função, objeto, array e etc...

JavaScript Fundamentos, estruturas, função, array e etc... Atividades praticas detalhadas e comentadas para todo mundo entender cada tag, bons estudos

Feb 27, 2022

Complete JavaScipt Array methods Cheatsheet 🚀

Complete JavaScipt Array methods Cheatsheet 🚀

Javascript Array Cheatsheet 👾 Click to download ☝ Important 🚨 There is no way this is perfect or include all the methods. I'll try to fix/add more m

Dec 7, 2022

Draft specification for a proposed Array.fromAsync method in JavaScript.

Array.fromAsync for JavaScript ECMAScript Stage-1 Proposal. J. S. Choi, 2021. Specification available Polyfill available Why an Array.fromAsync method

Dec 14, 2022

Analisador de números utilizando Array JavaScript com Html 5 e CSS 3

Olá pessal, tudo bem? :D Esse site foi desenvolvido para analisar números armazenados em um array chamado "dados[]". Temos dois botões um input e uma

Jan 6, 2022

A simple module to get porperties of an array

A simple module to get statistical porperties of an array. Currently the possible properties are mean, stdev and variance.

Nov 29, 2022
Owner
null
Hierarchical Converter for Array of Objects

Conversor Hierárquico para Array de Objetos - Hierarchical Converter to Array of Objects Docker-compose Cria a interface network e containers indicado

Victor Vinícius Eustáquio de Almeida 2 Jan 27, 2022
🎲 Extract one or more random elements from a weighted array (aka loot table or gacha)

wrand Extract one or more random elements from a weighted array. const items = [ { original: "Bronze", weight: 20 }, { original: "Silver", weight:

Leonardo Montini 14 Dec 2, 2022
javascript library to convert a list of objects to a nested json output format, depending on the names in the list

formToNestedJson javascript "library" to convert a list of objects to a nested json output format, depending on the names in the list Basic usage Give

null 2 Aug 2, 2021
Plugin that lets you create diagrams from textual representation (aka 'Diagrams as Code') within Logseq

Logseq - Diagrams as Code Plugin that lets you create diagrams (and other visualizations) from textual representation (aka 'Diagrams as Code') within

Nicolai P. Großer 80 Dec 21, 2022
MidJourney is an AI text-to-image service that generates images based on textual prompts. It is often used to create artistic or imaginative images, and is available on Discord and through a web interface here.

Midjourney MidJourney is an AI text-to-image service that generates images based on textual prompts. It is often used to create artistic or imaginativ

Andrew Tsegaye 8 May 1, 2023
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
Export your HTML table to Excel format.

excelExport Export your HTML tables to Excel format. Doc Installation Simply import JQuery & excel-export into your HTML. <script src="https://code.jq

Zenoo 1 Apr 22, 2021
A table component for your Mantine data-rich applications, supporting asynchronous data loading, column sorting, custom cell data rendering, row context menus, dark theme, and more.

Mantine DataTable A "dark-theme aware" table component for your Mantine UI data-rich applications, featuring asynchronous data loading support, pagina

Ionut-Cristian Florescu 331 Jan 4, 2023
Another table select prompt plugin of inquirer.js, with powerful table render and filters.

inquirer-table-select-prompt Table row selection prompt for Inquirer.js 动机 现有的 inquirer.js 没有支持表格行选中的命令行交互的插件. 社区内能查找到的,只有一个二维数组的 checkbox,eduardobouc

锂电 3 Jan 7, 2023
A command-line tool to convert Project Zomboid map data into Deep Zoom format

pzmap2dzi pzmap2dzi is a command-line tool running on Windows to convert Project Zomboid map data into Deep Zoom format. Features Supports both python

Min Xiang 14 Dec 31, 2022