skip to Main Content

I am a beginner. generateTable() is called in the onload() of the body tag. The link is planned to open the api with a parameter. The parameter is a number. In the function getTheadNames() json structure from which I take data to create the table.

function generateTable() {
  const jsons = "";
  const obj = JSON.parse(jsons);
  const tbl = document.createElement("table");

  let caption = document.createElement("caption");
  caption.textContent = "test";
  tbl.appendChild(caption);

  const tblHead = document.createElement("thead");
  const tblBody = document.createElement("tbody");

  var row = document.createElement("tr");
  var cell = document.createElement("th");

  createPartOfTable(row, cell);

  tblHead.appendChild(row);
  tbl.appendChild(tblHead);

  for (let i = 0; i < obj.length; i++) {
    row = document.createElement("tr");
    cell = document.createElement("td");
    createPartOfTable(row, cell, i, obj);
    tblBody.appendChild(row);
  }

  tbl.appendChild(tblBody);
  document.body.appendChild(tbl);
  tbl.setAttribute("class", "table");
}

function getTheadNames() {
  return ["number", "date", "warehouse", "packed", "base", "comment", "total"];
}

function createPartOfTable(row, cell, i = 0, obj = null) {
  let names = getTheadNames();
  for (let j = 0; j < names.length; j++) {
    var nameNode = names[j];
    cell = document.createElement(cell.nodeName);
    if (cell.nodeName == "TH") var cellText = document.createTextNode(nameNode);
    else {
      var textNode = obj[i][Object.keys(obj[i])[j] || {}];
      if (nameNode == "number") {
        const linkText = document.createTextNode(textNode);
        const link = document.createElement("a");
        link.href = "APIlink?number=" + textNode;
        link.appendChild(linkText);
        cellText = link;
      } else cellText = document.createTextNode(textNode);
    }
    cell.appendChild(cellText);
    row.appendChild(cell);
  }
}

Please tell me how I can improve my algorithm and what mistakes I made. I would like the code to be easier to read. Maybe there is a solution in some libraries I don’t know about.
The code itself works and creates a table, example json below

[
{
    "number": "000000001",
    "date": "2023-11-14T10:26:00",
    "warehouse": "test",
    "packed": "user",
    "base": "",
    "comment": "",
    "total": 1
},
{
    "number": "000000002",
    "date": "2023-11-14T10:26:00",
    "warehouse": "test",
    "packed": "user",
    "base": "",
    "comment": "test",
    "total": 1
}]

2

Answers


  1. table element have specific method you should use : https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement

    const 
      data = 
        [ { number: '000000001', date: '2023-11-14T10:26:00', warehouse: 'test', packed: 'user', base: '', comment: '',     total: 1 } 
        , { number: '000000002', date: '2023-11-14T10:26:00', warehouse: 'test', packed: 'user', base: '', comment: 'test', total: 1 } 
        ] 
    , colNames = Object.keys(data[0])
    , table    = document.body.appendChild(document.createElement('table'));
      ;
    table.createCaption().textContent = 'test (caption)'
      ;
    let
      tHead = table.createTHead() 
    , tBody = table.createTBody() 
    , rowX  = tHead.insertRow()
      ;
    colNames.forEach(cn => rowX.insertCell().textContent = cn)
      ; 
    data.forEach( obj =>
      {
      rowX = tBody.insertRow();
      colNames.forEach( cn => rowX.insertCell().textContent = obj[cn] );
      });
    html {
      font-family     : Arial, Helvetica, sans-serif;
      font-size       : 16px;
      }
    table {
      border-collapse  : separate;
      border-spacing   : 1px;
      background-color : darkblue;
      margin           : 1em;
      color            : black;
      }
    table td {
      background-color : whitesmoke;
      padding          : .2em .6em;
      min-width        : 4.2em;
      text-align       : center;
      }
    table thead td {
      padding          : .3em .6em;
      background-color : #3acec2;
      font-weight      : bold;
      }
    table caption {
      font-size : 1.2em;
      padding   : .3em 0;
      }
    Login or Signup to reply.
  2. Here is another, template based, way of doing the same job. In the end it is a question of style, which way you actually prefer.

    const 
      data = 
        [ { number: '000000001', date: '2023-11-14T10:26:00', warehouse: 'test', packed: 'user', base: '', comment: '',     total: 1 } 
        , { number: '000000002', date: '2023-11-14T10:26:00', warehouse: 'test', packed: 'user', base: '', comment: 'test', total: 1 } 
        ];
    function oToTr(o,quant){
     return "<tr>"+Object[quant=="keys"?quant:"values"](o).map(k=>`<td>${k}</td>`).join("")+"</tr>";
    }
    document.body.insertAdjacentHTML("beforeend",`<table><caption>Some table heading</caption>
       <thead>${oToTr(data[0],"keys")}</thead>
       <tbody>
       ${data.map(oToTr).join("n")}</tbody>
       </table>`);
    html {
      font-family     : Arial, Helvetica, sans-serif;
      font-size       : 16px;
      }
    table {
      border-collapse  : collapse;
      border: 3px solid #444;
      }
    table td {
      background-color : whitesmoke;
      border: 2px solid #444;
      padding          : .2em .6em;
      min-width        : 4.2em;
      text-align       : center;
      }
    table thead td {
      padding          : .3em .6em;
      background-color : #3acec2;
      font-weight      : bold;
      }
    table caption {
      font-size : 1.2em;
      padding   : .3em 0;
      }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search