console.table Tabularizes Arrays And Objects

Print object arrays as aligned tables with console.table: an optional columns list hides noise, plain objects tabulate by keys, deep data flattens first.

JavascriptCli Tooling

Code

javascriptsnippet
16 lines
// console.table:把对象数组渲染成带索引的表格,调试时不用手写对齐
const stages = [
  { stage: 'parse', ms: 12, ok: true },
  { stage: 'render', ms: 84, ok: true },
  { stage: 'upload', ms: 9, ok: false },
];
console.table(stages);

// 第二个参数指定列:隐藏噪声字段
console.table(stages, ['stage', 'ok']);

// 普通对象也能按键列表格,值列对齐键名
console.table({ pool: 8, busy: 3, idle: 5 });

// 深层数据先拍平成标量再进表:表格只显示一层字段
console.table(stages.map((s) => ({ ...s, ok: s.ok ? 'pass' : 'fail' })));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

┌─────────┬──────────┬────┬───────┐
│ (index) │ stage    │ ms │ ok    │
├─────────┼──────────┼────┼───────┤
│ 0       │ 'parse'  │ 12 │ true  │
│ 1       │ 'render' │ 84 │ true  │
│ 2       │ 'upload' │ 9  │ false │
└─────────┴──────────┴────┴───────┘
┌─────────┬──────────┬───────┐
│ (index) │ stage    │ ok    │
├─────────┼──────────┼───────┤
│ 0       │ 'parse'  │ true  │
│ 1       │ 'render' │ true  │
│ 2       │ 'upload' │ false │
└─────────┴──────────┴───────┘
┌─────────┬────────┐
│ (index) │ Values │
├─────────┼────────┤
│ pool    │ 8      │
│ busy    │ 3      │
│ idle    │ 5      │
└─────────┴────────┘
┌─────────┬──────────┬────┬────────┐
│ (index) │ stage    │ ms │ ok     │
├─────────┼──────────┼────┼────────┤
│ 0       │ 'parse'  │ 12 │ 'pass' │
│ 1       │ 'render' │ 84 │ 'pass' │
│ 2       │ 'upload' │ 9  │ 'fail' │
└─────────┴──────────┴────┴────────┘

How it works

Everything operates on top-level bindings: stages.

stages is an array of three objects; console.table(stages) renders it with an auto-generated (index) column plus one column per key (stage, ms, ok). Passing ['stage', 'ok'] as the second argument hides the ms column. A plain object like { pool: 8, busy: 3, idle: 5 } tabulates its keys as rows, and the final call maps each row through s.ok ? 'pass' : 'fail' so booleans print as quoted strings in the table.

Statements that matter

console.table(stages.map((s) => ({ ...s, ok: s.ok ? 'pass' : 'fail' })));

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `stages`.