Jansen Su
Jansen Su

Reputation: 113

How to put table with data array in javascript

I have my javascript with a function to add tables with loop but i want to add the format tables with my data from my json and send it to my email but when i send it, it always empty. The result should be tables with automaticly insert all data with tables there.

and the json that show up is always like this Items [ { org: four, online: true, id: 1, endpoint: ovcx } ]

let tableContent = ""
let stats = document.getElementById("status")

function tables() {
    tableContent += `<thead><tr><th class="tc-head" colspan="5">` + data[i].org + "</th></tr></thead>"

        + `<tr><td class="tc-row">ID</td><td class="tc-row">EndPoint</td><td class="tc-row">Updated At</td><td class="tc-row">Exp</td><td class="tc-row">Status</td></tr></tbody>`
}

function tablesinfo() {
    tableContent +=

        `<tbody><tr><td class="tc-col">` + data[j].id + "</td>"

        + `<td class="tc-col">` + data[j].endpoint + "</td>"

        // + `<td class="tc-col">` + data[j].updatedAt + "</td>"

        // + `<td class="tc-col">` + data[j].exp + "</td>"

        + `<td id="status">` + data[j].online + "</td>"
}

//  let data = [
//      { org: "Four", id: "1", endpoint: "ovcx", online: "True" },
//      { org: "Four", id: "2", endpoint: "ovcx", online: "False" },
//      { org: "Four", id: "3", endpoint: "ovcx", online: "True" },
//      { org: "Four", id: "4", endpoint: "ovcx", online: "False" },
//      { org: "BMW", id: "1", endpoint: "ovcx", online: "True" },
//      { org: "BMW", id: "2", endpoint: "ovcx", online: "True" },
//  ]

for (i = 0; i < data.length; i++) {
    if (i == 0) {
        tables()
        for (j = 0; j < data.length; j++) {
            if (data[i].org == data[j].org) {
                tablesinfo()
                
                // if (data[j].online == false && data[j].online == filter[j].online) {
                //     stats[j].classList.add('red');
                // }
                // else if (filter[j] && data[j].online == false) {
                //     stats[j].classList.add('white')
                // }
                // else {
                //     stats[j].classList.add('green');
                // }
            }
            else if (data[j].org != data[j].org) {
                j++
            }
        }
    }
    else if (data[i].org != data[i - 1].org) {
        tables()
        for (j = 0; j < data.length; j++) {
            if (data[i].org == data[j].org) {
                tablesinfo()
                // if (data[j].online == false) {
                //     stats[j].classList.add('red');
                // }
                // else if (filter[j] && data[j].online == false) {
                //     stats[j].classList.add('white')
                // }
                // else {
                //     stats[j].classList.add('green');
                // }
            }
            else if (data[j].org != data[j].org) {
                j++
            }
        }
    }
}

output.innerHTML = tableContent;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Charger Station Status</title>
    <style type="text/css">
      .tc {
        border-collapse: collapse;
        border-color: #9abad9;
        border-spacing: 0;
      }
      .tc td {
        background-color: #ebf5ff;
        border-color: #9abad9;
        border-style: solid;
        border-width: 1px;
        color: #444;
        font-family: Arial, sans-serif;
        font-size: 14px;
        overflow: hidden;
        padding: 10px 5px;
        word-break: normal;
      }
      .tc th {
        background-color: #409cff;
        border-color: #9abad9;
        border-style: solid;
        border-width: 1px;
        color: #fff;
        font-family: Arial, sans-serif;
        font-size: 14px;
        font-weight: normal;
        overflow: hidden;
        padding: 10px 5px;
        word-break: normal;
      }
      .tc .tc-row {
        background-color: #efefef;
        border-color: inherit;
        text-align: center;
        vertical-align: top;
      }
      .tc .tc-head {
        background-color: #9aff99;
        border-color: inherit;
        font-weight: bold;
        text-align: center;
        vertical-align: top;
      }
      .tc #status {
        border-color: inherit;
        text-align: left;
        vertical-align: top;
      }
      .tc .tc-col{
        border-color: inherit;
        text-align: left;
        vertical-align: top;
      }
      .red{
        background-color: red;
        color: blue;
      }
      .green{
        color: #409cff;
        background-color: green;
      }
      .green{
        color: #000000;
        background-color: white;
      }
      @media screen and (max-width: 767px) {
        .tc {
          width: auto !important;
        }
        .tc col {
          width: auto !important;
        }
        .tc-wrap {
          overflow-x: auto;
          -webkit-overflow-scrolling: touch;
        }
      }
    </style>
  </head>
  <body>
    <header>test</header>
    <div class="tc-wrap">
      <table class="tc" id="output">
      </table>
    </div>
    <script src="script.js"></script>
  </body>
  
</html>

async function listItems(){
  try {
    console.log('========data scan=======');
    const data = await docClient.scan( params ).promise()
    const filter = data.Items.filter( ( item ) => !item.online && item.exp <= Math.floor( ( new Date( Date.now() ) ).getTime() / 1000.0 ) )
    console.log('filter', filter)
    const scanning = fs.readFileSync(
      `./table.html`,
      "utf8")

    if ( filter.length >= 1 ) {
      const to = '[email protected]';
      const subject = 'EV Scanning Data!!!';
      const text = mustache.render(scanning, { ...data, ...filter })
      const send = await sendEmail( to, subject, text );
      console.log( 'send', send, 'data', data );

      filter.map( item => {  
        let putItemParams = {
          TableName: tableListStation,
          Item: {
            id: item.id,
            org: item.org,
            online: item.online,
            endpoint: item.endpoint,
            exp: Math.floor( ( new Date( Date.now() + 172800000 ) ).getTime() / 1000.0 ),
            updatedAt: momentGetDateJKT()
          }
        };
        console.log('item params', putItemParams)
        docClient.put( putItemParams, ( err, datadb ) => {
          if ( err ) {
            console.log('error push')
            return({ message: err.message });
          } else {
            console.log('oke', datadb)
            return data;
          }
        } );
      })
    }
    return data
  } catch (err) {
    return err
  }
}

I want it to be like this ignore exp and status

Upvotes: 0

Views: 266

Answers (1)

Bacem W.
Bacem W.

Reputation: 102

you will find here how do you should process json data as described below :

function myFunction() {

    var jsondata = '[{"org":"four","online":true,"id": 1,"endpoint": "ovcx"},' + 
                    '{"org":"four","online":true,"id": 1,"endpoint": "ovcx"},' +
                    '{"org":"bmw","online":true,"id": 1,"endpoint": "ovcx"},' + 
                    '{"org":"bmw","online":true,"id": 1,"endpoint": "ovcx"}]';

    var jsonobj = JSON.parse(jsondata);
    let tableContent = ""
    let stats = document.getElementById("mytab")
    let headers = []

    // find headers 
    for (var i = 0; i < jsonobj.length; i++){
      var obj = jsonobj[i];
      var h = obj.org;
      // find header into headers tab 
      if (!findHeader (headers, h)) {
          headers.push (h);
      }
    }
    

    // build tables
    var gtab = "<table>";   
    for (var i = 0; i < headers.length; i++){
      var h = headers[i];
      gtab = gtab + '<tr>'
      var stab = "<table>"; 
      stab = stab + '<th>' + h + '</th>'; 
      // manage data
      for (var j = 0; j < jsonobj.length; j++){
          var obj = jsonobj[j];
          if (h === obj.org) {
            stab = stab + '<tr>'; 
            stab = stab + '<td>' + obj.id + ',</td>'; 
            stab = stab + '<td>' + obj.endpoint + ',</td>'; 
            stab = stab + '<td>' + obj.online + ',</td>'; 
            stab = stab + '</tr>'; 
          }

        
      }
      stab = stab  + "</table>";    
      gtab = gtab + stab;
      gtab = gtab + '</tr>'
    }
    
    gtab = gtab + "</table>";   
    
    console.log (gtab);
    stats.innerHTML = gtab;
}
  function findHeader (headers, h) { 
    
    for (var i = 0; i < headers.length; i++){
        if (headers[i] === h) {
            return true;
        }
    }
    
    return false;
}

the html block to add generated data (without css)

<!DOCTYPE html>
<html>

   <head>
      <title>Javascript External Script</title>
      <script src = "script.js" type = "text/javascript"/></script>
   </head>

    <body onload="myFunction()">
        <div id="mytab">
        </div>
   </body>

</html>

Should give something like this in view (add css to have the right render)

enter image description here

hope this will help,

Upvotes: 1

Related Questions