0

对 Web 开发相当陌生。我需要一些帮助将 JSON 转换为表(转置)。

我想从 API 调用中检索以下格式的 JSON

{'name': John
 'age': 18
 'enrolled': ['math','science','english']
} 

并将其转换为

|---------------------|-----------------------------|
|      name           |     John                    |
|---------------------|-----------------------------|
|      age            |       18                    |
|---------------------|-----------------------------|
|      enrolled       | ['math','science','english']|
|---------------------|-----------------------------|
4

1 回答 1

2

没有处理中心对齐内容,但您可以通过以下方式转置和格式化矩阵:

  1. 将 JSON 转换为矩阵
  2. 转置行和列
  3. 使用字符串值创建格式化矩阵
  4. 使用显示值计算每列的宽度
  5. 格式化要打印的矩阵

let data = [
   { "name": "John",   "age": 77, "enrolled": [ "science" ] },
   { "name": "Paul",   "age": 79, "enrolled": [ "math",   ] },
   { "name": "George", "age": 76, "enrolled": [ "english" ] },
   { "name": "Ringo",  "age": 79, "enrolled": [ "music"   ] }
]

let matrix = transposeMatrix(jsonToMatrix(data))

document.body.appendChild(matrixToTable(matrix));
console.log(formatMatrix(matrix));

function jsonToMatrix(jsonData) {
  let keys = Object.keys(jsonData[0])
  return [keys, ...jsonData.map(item => keys.map(key => item[key]))]
}

function transposeMatrix(matrix) {
  return matrix[0].map((col, i) => matrix.map(row => row[i]))
}

function matrixToTable(matrix) {
  let tableEl = document.createElement('table')
  matrix.forEach(row => {
    let trEl = document.createElement('tr')
    row.forEach(col => {
      let tdEl = document.createElement('td')
      tdEl.textContent = col
      trEl.appendChild(tdEl)
    });
    tableEl.appendChild(trEl)
  })
  return tableEl
}

function formatMatrix(matrix) {
  let formattedValues = matrix.map(row => row.map(col => ' ' + JSON.stringify(col) + ' '))
  let colWidths = formattedValues[0].map(col => 0)
  formattedValues.forEach(row => {
    row.forEach((col, index) => {
      if (col.length > colWidths[index]) {
        colWidths[index] = col.length
      }
    })
  })
  let width = colWidths.reduce((total, colWidth) => total + colWidth, 0)
  let separator = '+' + colWidths.map(colWidth => '-'.repeat(colWidth)).join('+') + '+' + '\n'
  return [
    separator,
    formattedValues.map(row => {
      return [
        '|',
        row.map((col, index) => col.padEnd(colWidths[index], ' ')).join('|'),
        '|\n'
      ].join('')
    }).join(separator),
    separator
  ].join('')
}
table { border-collapse: collapse; }
table, td { border: thin solid grey; }
td { padding: 0.25em; }

于 2020-01-08T15:50:11.660 回答