【发布时间】:2018-09-12 01:42:40
【问题描述】:
我正在控制台中查看一组数据。
console.table(myArray) 始终将索引作为第一列。
这在查看对象数据时很好,当索引是键时,但当索引是数组索引时则不行(在我的情况下,它会分散/烦人/从内容中删除)。
有没有办法在没有这个索引的情况下显示表格?
可选的columns 参数允许只显示想要的列...除了索引。
【问题讨论】:
-
怀疑你可以隐藏它
我正在控制台中查看一组数据。
console.table(myArray) 始终将索引作为第一列。
这在查看对象数据时很好,当索引是键时,但当索引是数组索引时则不行(在我的情况下,它会分散/烦人/从内容中删除)。
有没有办法在没有这个索引的情况下显示表格?
可选的columns 参数允许只显示想要的列...除了索引。
【问题讨论】:
如MDN Web docs所示
表中的第一列将被标记(索引)。如果数据是一个数组,那么它的值就是数组索引。如果数据是一个对象,那么它的值就是属性名称。请注意(在 Firefox 中)console.table 仅限于显示 1000 行(第一行是标记的索引)。
所以对于一个数组,你不能隐藏要显示的索引键。但是,作为一种解决方法,您可以将数组转换为使用 您的 键的对象。
示例:(打开控制台查看结果)
const array = [{myId: 42, name: 'John', color: 'red'}, {myId: 1337, name: 'Jane', color: 'blue'}]
const transformed = array.reduce((acc, {myId, ...x}) => { acc[myId] = x; return acc}, {})
console.table(transformed)
【讨论】:
如果您使用的是节点(而不是浏览器)并且您想要一个不引入依赖项的解决方案,您可以这样做:
(以this answer为基础):
const { Console } = require('console');
const { Transform } = require('stream');
function table(input) {
// @see https://stackoverflow.com/a/67859384
const ts = new Transform({ transform(chunk, enc, cb) { cb(null, chunk) } })
const logger = new Console({ stdout: ts })
logger.table(input)
const table = (ts.read() || '').toString()
let result = '';
for (let row of table.split(/[\r\n]+/)) {
let r = row.replace(/[^┬]*┬/, '┌');
r = r.replace(/^├─*┼/, '├');
r = r.replace(/│[^│]*/, '');
r = r.replace(/^└─*┴/, '└');
r = r.replace(/'/g, ' ');
result += `${r}\n`;
}
console.log(result);
}
const test = [
{ name: "Jane", id: '1234', pastime: 'Archery' },
{ name: "John", id: '1235', pastime: 'Knitting' },
{ name: "Jess", id: '1236', pastime: 'Fishing' }
];
table(test);
此表中没有索引列的结果:
┌────────┬────────┬────────────┐
│ name │ id │ pastime │
├────────┼────────┼────────────┤
│ Jane │ 1234 │ Archery │
│ John │ 1235 │ Knitting │
│ Jess │ 1236 │ Fishing │
└────────┴────────┴────────────┘
【讨论】: