1

I'm trying to loop through all user's comments, but with an if statement looking for a certain value. Problem is my app breaks as some users havent made comments, and therefore i get a 'cannot read property of 'collected' undefined. How do I skip over undefined values for the if statement? the code is below:

<% for(var i=0; i < users.length; i++) { %>
   <tr>


    <% if(users[i].comments.slice(-1)[0].collected !== 'At Reception') { %>

     <td>Nothing in reception - well done!</td>

    <%  } else { %>



     <td><%= users[i].studio %></td>
     <td><%= users[i].name %></td>
     <td><%= users[i].email %></td>
     <td><%= users[i].username %></td>
     <td><%= users[i].comments.slice(-1)[0].collected %></td>

     <td><a class="btn btn-primary" href="/users/<%= users[i]._id %>">More Info</a></td>

    <% } %>
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Adam Furniss
  • 37
  • 1
  • 6

3 Answers3

2

First check if that property is available to that object by using this line of code:

yourObject.hasOwnProperty('collected') // it will return true if exist, false if not.

if(yourObject.hasOwnProperty('collected')) {
  // code here...
} else {
  // catch here...
}

Try to read more information about Object.prototype.hasOwnProperty()

Jrey
  • 1,618
  • 2
  • 17
  • 34
1

Just add a check to see if the object exists, and if the comments length is > 0:

<% for(var i=0; i < users.length; i++) { %>
   <tr>

    <% if(!users[i].comments || users[i].comments.length == 0) {
          continue;
    } else if(users[i].comments && users[i].comments.length > 0 && users[i].comments.slice(-1)[0].collected !== 'At Reception') { %>

     <td>Nothing in reception - well done!</td>

    <%  } else { %>
  <% console.log('nothing in reception') %>

 <td><%= users[i].studio %></td>
 <td><%= users[i].name %></td>
 <td><%= users[i].email %></td>
 <td><%= users[i].username %></td>
 <td><%= users[i].comments.slice(-1)[0].collected %></td>

 <td><a class="btn btn-primary" href="/users/<%= users[i]._id %>">More Info</a></td>

<% } %>
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47
0

Did you try continue;? I know that you can put that inside a block somewhere. Were if it doesn't meet the standards of your condition it'll skip and iterate to the next comment/list.