NodeJS 多行`console.table({a:“aaa\naaa”,B:“bbb\nbbb”})`用于节点

mqxuamgl  于 2023-03-29  发布在  Node.js
关注(0)|答案(4)|浏览(93)

有什么方法可以在节点中绘制多行表格吗?我试过了:

console.table({a: "aaa\naaa", b: "bbb\nbbb"})

但这只是删除所有的换行符:

kd3sttzy

kd3sttzy1#

溶液#1

试试这个,但不确定它是否是一个好的解决方案:

console.table(
  {
    a: "aaa",
    "": "aaa",
    b: "bbb",
    " ": "bbb"
  }
)

输出:

溶液#2

我们的想法是不要弄乱默认索引并创建自己的列label

console.table([
  { Label: "a", Values: "aaa" },
  { Values: "aaa" },
  { Label: "b", Values: "bbb" },
  { Values: "bbb" },
]);

输出:

polkgigr

polkgigr2#

感谢Dheemanth Bhat的惊人想法,该解决方案建立在此基础上:

/**
 * @param {object} data
 * @see https://stackoverflow.com/questions/66614444/multiline-console-tablea-aaa-naaa-b-bbb-nbbb-for-node
 */

export function consoleTableNewline(data) {
  var tmp = [];
  for (var i in data) {
    var val = data[i];
    var parts = val.split('\n');
    var maxLen = parts.reduce((acc, cur) => Math.max(cur.length, acc), 0);
    parts = parts.map(x=>x.padEnd(maxLen));
    for (var j=0; j<parts.length; j++) {
      var part = parts[j];
      var key = i;
      var obj = {};
      if (j == 0) {
        obj.key = key;
      }
      obj.val = part;
      tmp.push(obj);
    }
  }
  console.table(tmp);
}

它负责创建一个漂亮的输出(所有行的长度都完全相同,否则它看起来会高度失真)。

2sbarzqh

2sbarzqh3#

根据其他的答案,我最终使用了这个。感谢之前的工作!
应该适用于具有任意键/值对的任何对象列表。
可以传递可选的maxColWidth consoleTableWithWrapping(change, 90) // 90 chars max

function wrapItemToMultipleRows<Type>(item: Type, maxCellWidth: number): Array<Type> {
  const isRemainingData = Object.values(item).find(value => {
    return value && value.length > 0;
  });

  if (!isRemainingData) {
    return [];
  }

  const itemRow: Type = {} as Type;
  const remaining: Type = {} as Type;
  Object.entries(item).forEach(([key, value]) => {
    itemRow[key as keyof typeof itemRow] = value?.slice ? value.slice(0, maxCellWidth) : '';
    remaining[key as keyof typeof itemRow] = value?.slice ? value.slice(maxCellWidth) : '';
  });

  return [itemRow, ...wrapItemToMultipleRows(remaining, maxCellWidth)];
}

function consoleTableWithWrapping<Type>(data: Array<Type>, maxCellWidth = 90) {
  let tableItems: Array<Type> = [];

  data.forEach(item => {
    tableItems = [...tableItems, ...wrapItemToMultipleRows(item, maxCellWidth)];
  });

  console.table(tableItems);
}
consoleTableWithWrapping([
  {
    sheet: 'One',
    cell: 'C8',
    old: 'no result?',
    new: '',
  },
  ...
]);

┌─────────┬─────────────┬────────┬──────────────────────────────────────────────┬───────────────────────────────────────────────────┐
│ (index) │    sheet    │  cell  │                     old                      │                        new                        │
├─────────┼─────────────┼────────┼──────────────────────────────────────────────┼───────────────────────────────────────────────────┤
│    0    │    'One'    │  'C8'  │                 'no result?'                 │                        ''                         │
│    1    │    'One'    │ 'I140' │               '=Expenses!B16'                │                  '=Expenses!B8'                   │
│    2    │    'One'    │ 'C141' │  "Enter living expenses in the 'Expenses' "  │    "Enter living expenses in the 'Expenses' "     │
│    3    │     ''      │   ''   │  'tab below – total monthly living expense'  │    'tab below - total monthly living expense'     │
│    4    │     ''      │   ''   │    '\ns will flow through to this field.'    │      '\ns will flow through to this field.'       │
│    5    │    'One'    │ 'C142' │ 'Other significant expenses \r\nEnter other' │    'All fixed and other significant expenses'     │
│    6    │     ''      │   ''   │  " significant expenses in the 'Expenses' "  │   ' \r\nEnter fixed and other significant exp'    │
│    7    │     ''      │   ''   │ 'tab below – total monthly oth\ner signifi'  │    "enses in the 'Expenses' tab below – tota"     │
│    8    │     ''      │   ''   │  'cant expenses will flow through to this '  │    'l m\nonthly fixed and other significant e'    │
│    9    │     ''      │   ''   │                   'field.'                   │    'xpenses will flow through to this field.'     │
│   10    │    'One'    │ 'F142' │  '=IF(AND(OR(G142="",G142=0),OR(I142="",I1'  │    '=IF(AND(OR(G142="",G142=0),OR(I142="",I1'     │
│   11    │     ''      │   ''   │  '42=0)), "Other significant expenses from'  │    '42=0)), "All fixed and other significant'     │
│   12    │     ''      │   ''   │ `\n the 'Expenses' tab", IF(AND(OR(G142=""`  │    `\n expenses from the 'Expenses' tab", IF(`    │
│   13    │     ''      │   ''   │  ',G142>=0),I142>0), "Other significant ex'  │    'AND(OR(G142="",G142>=0),I142>0), "Other '     │
│   14    │     ''      │   ''   │ `p\nenses from the 'Expenses' tab","NOTE: `  │    "s\nignificant expenses from the 'Expenses"    │
│   15    │     ''      │   ''   │  'Enter value of expense in the adjacent c'  │    `' tab","NOTE: Enter value of expense in `     │
│   16    │     ''      │   ''   │                  'el\nl"))'                  │             'th\ne adjacent cell"))'              │
│   17    │    'One'    │ 'I142' │               '=Expenses!B46'                │                  '=Expenses!B25'                  │
wnavrhmk

wnavrhmk4#

你可以试试这样。
1.对象数组。

let a = {firstName:"Jane", lastName:"Smith"};
let b = {firstName:"John", lastName:"Smith"};
let c = {firstName:"Emily", lastName:"Smith"};
console.table([a, b, c]);

1.属性为对象的对象

var family = {};
family.a = {firstName:"Jane", lastName:"Smith"};
family.b = {firstName:"John", lastName:"Smith"};
family.c = {firstName:"Emily", lastName:"Smith"};
console.table(family);

相关问题