0

Fairly new to web development. I need some help with converting a JSON into a table (transposed).

I want to retrieve a JSON in the below format from an API call

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

and convert this to

|---------------------|-----------------------------|
|      name           |     John                    |
|---------------------|-----------------------------|
|      age            |       18                    |
|---------------------|-----------------------------|
|      enrolled       | ['math','science','english']|
|---------------------|-----------------------------|
jon
  • 429
  • 6
  • 15
  • 1
    Have a look at this solution: https://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table – Nicola Lepetit Jan 08 '20 at 15:16
  • 1
    Does this answer your question? [Convert json data to a html table](https://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table) – johannchopin Jan 08 '20 at 15:19
  • Nope. I'm trying to get the table transposed. Also, I'm trying to find how should I load the JSON from an api call. – jon Jan 08 '20 at 15:33

1 Answers1

2

Did not handle center-justifying the content, but you can transpose and format the matrix by:

  1. Converting the JSON to a matrix
  2. Transposing the rows and columns
  3. Creating a formatted matrix with string values
  4. Figuring out each columns width using the display values
  5. Formatting the matrix to be printed

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132