I'm facing a weird situation right now, if I do this within my EJS template:
<%= JSON.stringify(course.results[0]) %>
that print me the following:
{
"user_id": "900",
"trainingpath_id": "25",
"sco_id": "1",
"nb": "11",
"date": "25/07/2018 14:14",
"date_last_update": "21/08/2018 13:10",
"lesson_status": "passed",
"spent_time": "278",
"score": "100",
"progression": "100",
"unique_sco_id": "427"
}
But if I do this:
<%= JSON.stringify(course.results[0].score) %>
I receive an error telling me that it Cannot read property 'score' of undefined
Someone ever experienced that ?
Actual template page :
<div class="container">
<div class="row heading-box">
<div class="col">
<h1><span id="introduction">Progress<br></span></h1>
</div>
</div>
<div class="row text-box">
<div class="col">
<% if (Array.isArray(sessions)) { %>
<% sessions.map(session=>{ %>
<div class="session-box">
<h4 class="session-title"><i class="fal fa-chevron-double-right title-indicator"></i> <%= session.name; %> </h4>
<% session.courses.map(course=>{%>
<div class="course-box">
<span class="fa-stack course-thumbnail-stack">
<i class="fas fa-circle course-thumbnail-circle ready fa-stack-2x"></i>
<i class="fal fa-play-circle course-thumbnail-action ready fa-stack-1x fa-inverse"></i>
</span>
<img src="<%= session.details[0].thumbnail_link.indexOf(lms_url) > -1 ? '' : `${lms_url}/` %><%= session.details[0].thumbnail_link %>" class="course-thumbnail">
<h4> <%= course.titre; %></h4>
<p>
Duration : <%= (session.details[0].typical_learning_time_duration || 0) / 60 %> mins<br/>
Score : <% if ('results' in course && Array.isArray(course.results)) { %><%= JSON.stringify(course.results[0], null, '\t') %><% } else { %><%= '0' %><% } %>%
</p>
<button type="button" class="btn btn-lg start-course" onclick="window.location='<%= course.lms_url %>>'">Start</button>
<div style="clear:both"></div>
</div>
<%});%>
</div>
<% }) %>
</div>
<% } %>
</div>
</div>
As discussed in the comments, there is nothing wrong with the scope you have, so probably you're having a problem with the array course.results
sometimes, meaning it might have no elements. So to avoid that just add length
check as suggested by @Kosala Nuwan Perera
Also you don't need to stringify
the score as it is a string already.
Try:
Score : <% if ('results' in course && Array.isArray(course.results) && course.results.length > 0) { %><%= course.results[0].score %><% } else { %><%= '0' %><% } %>
The only reason you'd get property 'score' of undefined
is if your results[0]
was undefined.
I'd suggest doing:
if(course && course.results && course.results.length) {
course.results[0].score
}
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.