[英]Javascript/NodeJS forEach Loop
我有這個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="/users/<%= user._id %>">More Info</a></td>
<% }); %>
我只想向用戶顯示具有'At Reception'
作為comment.collected
值的用戶,但我在確定如何執行此操作時遇到了問題。 任何幫助將非常感激。
編輯:
有問題的UserSchema如下所示:
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}
});
您應該首先過濾數組:
<% 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) { %>
...
注意:上面的代碼顯示至少有一個評論的用戶,其comment.collect === 'At Reception'
。 如果只想顯示其所有注釋收集屬性等於'At Reception'
,則使用Array#every
而不是Array#some
:
...
return user.comments.every(...);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.