Node.js如何将SQL查询返回的对象数组转为控制台格式化文本表格
Node.js 对象数组转控制台带边框表格实现方案
实现逻辑
- 自动提取输入数组的第一个对象的所有键作为表格表头,支持任意列数
- 自动计算每列的最大宽度(取表头长度和该列所有内容的字符串长度的最大值),适配不同长度的内容
- 自适应行数,不管返回多少行数据都可以正常生成表格
- 支持字符串、布尔值、数字等多种类型的内容自动转换为字符串展示
完整实现代码
function generateConsoleTable(dataArray) { // 处理空输入 if (!Array.isArray(dataArray) || dataArray.length === 0) { return '> 无查询数据' } // 提取表头 const headers = Object.keys(dataArray[0]) // 计算每列最大宽度 const columnWidths = headers.map(header => { const headerLen = header.length const maxContentLen = Math.max(...dataArray.map(row => String(row[header] || '').length)) return Math.max(headerLen, maxContentLen) }) // 生成边框分隔行 const getBorderLine = () => { return '+' + columnWidths.map(width => '-'.repeat(width + 2)).join('+') + '+' } // 生成内容行 const getContentRow = (rowItems) => { return '| ' + rowItems.map((item, idx) => String(item).padEnd(columnWidths[idx], ' ')).join(' | ') + ' |' } // 拼接所有行 const tableLines = [] tableLines.push(getBorderLine()) // 表头行:自动将键名首字母大写 tableLines.push(getContentRow(headers.map(h => h.charAt(0).toUpperCase() + h.slice(1)))) tableLines.push(getBorderLine()) // 数据行 dataArray.forEach(row => { const rowContent = headers.map(header => row[header] ?? '') tableLines.push(getContentRow(rowContent)) tableLines.push(getBorderLine()) }) return tableLines.join('\n') }
使用示例
// 测试示例1 const data1 = [ { id: '626916199783071750', birthdays: '10/3' }, { id: '797279656595947531', birthdays: '01/02' }, { id: '548976894576849555', birthdays: '3/24' } ] console.log(generateConsoleTable(data1)) // 测试示例2 const data2 = [ { id: '626916199783071750', username: 'whatever', idk: true }, { id: '797279656595947531', username: 'thing', idk: false}, { id: '7972656595947531', username: 'idk', idk: true }, { id: '874596745986988596', username: 'cooldude', idk: false } ] console.log(generateConsoleTable(data2))
内容的提问来源于stack exchange,提问作者Colin Frankel
相关产品推荐
相关产品推荐

