0

There is a small project at nodejs + express + postgres for self-education. By requesting Postgres I get data in json format, then the data on the express tools is rendered to the ejs template. The very question is how do I add this json to a dynamic table in html.

The request to the database looks like this

    const pool = new pg.Pool(config);

 router.get('/index', (req, res, next) => {
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query('SELECT * FROM srt_final WHERE info_init @> \'{"subscriber":"999999"}\' ORDER BY id DESC LIMIT 20', function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             var osaka = result.rows;

                     res.render('index', {  srt: osaka });
        })

    })
 });

The data itself looks like this (about 30 values).

    [
{"id":11653167,"info_init":
  {"date":"05.07.2018"},
   ....
  {"Time":"10:31:17"}
},
  ....
{"id":11653168,"info_init":
  {:},
    ......
  {:}
}
]

4 Answers 4

2

A little too late maybe, but the solutions I found didn't work quite well. I needed something simpler, not a template engine or a lib. Also, the mentioned npm package, html-tablify, didnt work for me when trying to generate a table from a Mongoose response. Btw, sorry for my bad english.

const row = html => `<tr>\n${html}</tr>\n`,
      heading = object => row(Object.keys(object).reduce((html, heading) => (html + `<th>${heading}</th>`), '')),
      datarow = object => row(Object.values(object).reduce((html, value) => (html + `<td>${value}</td>`), ''));
                               
function htmlTable(dataList) {
  return `<table>
            ${heading(dataList[0])}
            ${dataList.reduce((html, object) => (html + datarow(object)), '')}
          </table>`
}

const set = [
  {_id: 1234,
    usuario: 'user1',
    clave: 'pass1' },
  {_id: 12345,
    usuario: 'user2',
    clave: 'asdas' },
  {_id: 12357,
    usuario: 'user3',
    clave: 'asdasd' },
  {_id: 12376,
    usuario: 'user5',
    clave: 'asdasd' }
];

htmlTable(set)

Output:

<table>
  <tr>
    <th>_id</th>
    <th>usuario</th>
    <th>clave</th>
  </tr>   
  <tr>
     <td>123</td>
     <td>xD</td>
     <td>asd</td>
  </tr>
  <tr>
     <td>123</td>
     <td>xD</td>
     <td>asd</td>
  </tr>
  <tr>
     <td>123</td>
     <td>xD</td>
     <td>asd</td>
  </tr>
  <tr>
     <td>123</td>
     <td>xD</td>
     <td>asd</td>
  </tr>
</table>

How does it works... it is actually pretty simple. The row function wraps some value inside a tag. heading, on the other side, takes an object and creates the table heading html based on the object's own keys. datarow, takes an object, and genereate all the cells of the row Both heading and datarow functions returns a row html code by using the row function. htmlTable function receives a list of objects, and just returns the full table's html code.

With a few tweaks, markup formatting, attributes and styles can be easily added.

Sign up to request clarification or add additional context in comments.

Comments

0

Ref: How to create HTML table based on JSON

 var html = '<table class="table table-striped">';
    html += '<tr>';
    var flag = 0;
    $.each(data[0], function(index, value){
        html += '<th>'+index+'</th>';
    });
    html += '</tr>';
     $.each(data, function(index, value){
         html += '<tr>';
        $.each(value, function(index2, value2){
            html += '<td>'+value2+'</td>';
        });
        html += '<tr>';
     });
     html += '</table>';
     $('body').html(html);

2 Comments

Thank you for your answer, but in my cases when using this example, I get this result: id info_init info_final state 12293245 [object Object] [object Object] 1 12291387 [object Object] [object Object] 1
Ref: i created a example embed.plnkr.co/apjw1FF4Qu3yc1B3bSb6 because your object has some nested data inside the key "info_init"
0

It's not about NodeJS related question, you can look into html table how to make table in html. Then render dynamic contents by nodejs better is use a view engine like ejs.

7 Comments

Can you tell me how to bring out the contents of all "info_init".
info_init means ?
[ {"id":11653167,"info_init": {"date":"05.07.2018"}, .... {"Time":"10:31:17"} }, .... {"id":11653168,"info_init": {:}, ...... {:} } ]
That is, fill the table with content only "info_init"
Do u use any temple engine
|
0

Use html-tablify

https://www.npmjs.com/package/html-tablify

I will create html table from json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.