1

I want to convert a nested array to a HTML table where I have assign table_header.

Likewise, first subarray in Column_1 and second subarray in Column_2.

const arr = [
  [
    "abc",
    "gsdg",
    "fsvth",
    "rewurths",
    "ejgfjsgfns",
    "sdbqeqtjhbq"
  ],
  [
    "ryethabe"
  ]
]
<table id="table">
  <thead>
    <tr>
      <th>Column_1</th>
      <th>Column_2</th>
    </tr>
  </thead>
  <tbody id="table_data_response">
  </tbody>
</table>
  • Perhaps the following answer to another post on Stack Overflow has what you need: https://stackoverflow.com/a/51276151/3272066 (specifically, the function `append_json` in the answer). – Giorgio Feb 07 '21 at 08:31
  • I fixed your table html. It was invalid - what is the expected output? Draw a picture and show the JavaScript you tried – mplungjan Feb 07 '21 at 08:54

2 Answers2

1

Actually you have a 2D array. You can build a result string in a nested for-loop and build your table so dynamically and then insert it to a DOM-Element.

I made you a snippet.

const obj = [
  [
    "abc",
    "gsdg",
    "fsvth",
    "rewurths",
    "ejgfjsgfns",
    "sdbqeqtjhbq"
  ],
  [
    "ryethabe"
  ]
]

let resString = '<table><thead><tr><th>Col1</th><th>Col2</th></tr></thead><tbody>';

// Calculate which array has the bigger size, this is needed as running condition in the outer for-loop
let max;
obj[0].length > obj[1].length ? max = obj[0].length : max = obj[1].length;


for (let i = 0; i < max; i++) {
  resString += '<tr>';
  for (let j = 0; j < obj.length; j++) {
    if (obj[j][i] !== null && obj[j][i] !== undefined) {
        resString += `<td>${obj[j][i]}</td>`
      }
    }
    resString += '</tr>';
  }

  resString += '</tbody></table>';


  document.getElementById('bla').innerHTML = resString;
<div id="bla"> </div>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
1

Perhaps this?

const arr = [ ["abc", "gsdg", "fsvth", "rewurths", "ejgfjsgfns", "sdbqeqtjhbq"],  ["ryethabe"] ];

document.getElementById("table_data_response").innerHTML = ['<tr>', 
  ...arr.reduce((acc, item, i) => {
    const row = (acc[i] || '<td>') + item.join('<br/>') + '</td>';
    acc.push(row);
    return acc;
  }, []), '</tr>'].join("");
<table id="table">
  <thead>
    <tr>
      <th>Column_1</th>
      <th>Column_2</th>
    </tr>
  </thead>
  <tbody id="table_data_response">
  </tbody>
</table>
mplungjan
  • 169,008
  • 28
  • 173
  • 236