简体   繁体   English

在 node/express ejs 中使用 JSON.stringify( obj )

[英]Working with JSON.stringify( obj ) in node/express ejs

I'm trying to pass an object to my view using JSON.stringify but I am not sure how to access elements in the object.我正在尝试使用 JSON.stringify 将对象传递给我的视图,但我不确定如何访问对象中的元素。 Here is how I pass the object to my view:这是我如何将对象传递给我的视图:

const getTracking = (request, response) => {
    pool.query('SELECT * FROM tracking', (error, results) => {
        if (error) {
            throw error
        }
        var trackingObj = JSON.stringify(results.rows);
        response.render('pages/trackingInfo', {
            trackingObj: trackingObj
        });
    })
}

Then in my index.ejs document I can access my object like so:然后在我的 index.ejs 文档中,我可以像这样访问我的对象:

<p><%= trackingObj %></p>

which results in the following output in the browser (data is grabbed from postgres database):这会在浏览器中产生以下输出(数据是从 postgres 数据库中获取的):

[{"wo_num":1,"completion_date":"2021-08-04T04:00:00.000Z","material":"test","description":"test","qty":1,"total_hours":null},
{"wo_num":2,"completion_date":"2021-08-05T04:00:00.000Z","material":"test2","description":"test2","qty":2,"total_hours":2},

Is there a way to access the elements of this JSON.stringify object individually so I could do something like display them in a table?有没有办法单独访问这个 JSON.stringify 对象的元素,以便我可以做一些事情,比如在表格中显示它们?

 JSON.parse('<%- JSON.stringify(trackingObj) %>')

if you want to just see the content you can also use (will be displayed on the terminal如果只想看内容也可以使用(会在终端上显示

<% console.log(trackingObj) %>

for a better view :为了更好的观看:

<% console.table(trackingObj) %>

As @Jayesh commented, the solution was to access the object using indices like so: trackingObj[0].material正如@Jayesh 评论的那样,解决方案是使用如下索引访问对象: trackingObj[0].material

To then display the elements in a table you can iterate through them in the following manner:要在表格中显示元素,您可以按以下方式遍历它们:

<% trackingObj.forEach(function(obj) { %>
<tr>
   <td> <%= obj.material %> </td>
   <td> <%= obj.wo_num %> </td>
<tr>
<% } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM