2017-12-17 19 views
0

私はこのForeachループを持っている:Javascriptを/ NodeJS Foreachループ

<% users.forEach(function(user) { %> 
    <tr> 
    <td><%= user.studio %></td> 
    <td><%= user.name %></td> 
    <td><%= user.email %></td> 
    <td><%= user.username %></td> 
    <td> 
    <% user.comments.forEach(function(comment) { %> 
     <%= comment.collected %> 
    <% }); %> 
    </td> 
    <td ><a class="btn btn-primary" href="https://stackoverflow.com/users/<%= user._id %>">More Info</a></td> 
<% }); %> 

私は何をしたいだけcomment.collectedの値として'At Reception'を持つユーザーを示しているが、私は問題私はどうなる方法を考え出すを持っていますこの。どんな助けでも大歓迎です。

編集:

<% users.filter(function(user) {       // filter only users 
     return user.comments.some(function(comment) {  // that some (at least one) of their comments 
      return comment.collected === "At Reception";  // have its collected property equal to "At Reception" 
     }); 
    }).forEach(function(user) { %> 
... 

注:上記のコードは、持っているユーザーを示していますが、最初の配列をフィルタリングする必要があり

var UserSchema = new mongoose.Schema({ 
    username: {type: String, unique: true, required: true}, 
    name: {type: String, required: true}, 
    email: {type: String, unique: true, required: true}, 
    password: String, 
    studio: {type: String, required: true}, 
    resetPasswordToken: String, 
    resetPasswordExpires: Date, 

    comments: [ 
     { 
      quantity: String, 
      received: { type: Date, default: Date.now }, 
      collected: { type: String, default: "At Reception" } 
     } 
    ], 

    isAdmin: {type: Boolean, default: false} 
}); 
+0

'user.comments'は何ですか?アレイ? –

+0

こんにちは、はい、説明のために元の投稿にuserSchemaを追加しました –

+0

OK!すべての 'comments.collected === 'At Reception''を持つユーザーを表示したいのですか?または少なくとも1つのコメントだけ? –

答えて

0

問題のUserSchemaは、次のようになります少なくとも1つのコメントがcomment.collect === 'At Reception'です。あなたは'At Reception'に等しいすべての彼らのコメント収集したプロパティを持つユーザーのみを表示したい場合は、代わりにArray#someArray#everyを使用します。

... 
return user.comments.every(...); 
... 
+0

ありがとうございます!アレイのフィルタリングについて知りませんでした。何か新しいことを学んだことをうれしく思います –