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. 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:
<p><%= trackingObj %></p>
which results in the following output in the browser (data is grabbed from postgres database):
[{"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.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
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>
<% } %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.