如何将以下数组分组并输出到ejs中?
How to group the following array and output them in ejs?
这是数组:
const emails = [
{ email: 'w@w', createdAt: 2022-03-31T17:07:36.675+00:00 },
{ email: 'a@a', createdAt: 2022-03-31T17:07:36.675+00:00 },
{ email: 'w@b', createdAt: 2022-04-31T17:07:36.675+00:00 },
{ email: 'w@c', createdAt: 2022-04-31T17:07:36.675+00:00 },
{ email: 'w@d', createdAt: 2022-06-31T17:07:36.675+00:00 },
]
我想在ejs中这样格式化:
<div class='card'>
<h3>Unique Date</h3>
<div class='emails'>
<p>All the emails of that unique date</p>
</div>
</div>
我该怎么做?
在后端,您需要使用 reduce 和 map 对现有数组进行分组以执行以下操作。
// Group emails by date
const groupedEmails = emails.reduce((acc, curr) => {
const date = curr.createdAt.split('T')[0];
if (!acc[date]) {
acc[date] = [];
}
acc[date].push(curr);
return acc;
}, {});
// Loop through grouped emails
const groupedEmailsArray = Object.keys(groupedEmails).map(key => {
return {
date: key,
// Sort emails by email in alphabetical order
emails: groupedEmails[key].sort((a, b) => {
if (a.email < b.email) {
return -1;
}
if (a.email > b.email) {
return 1;
}
return 0;
})
}
});
然后您将希望将 groupedEmailArray
传递给您的视图并像这样呈现视图
<div class='card'>
<h3>Unique Date</h3>
<div class='emails'>
<p>All the emails of that unique date</p>
<% for(let group of groupedEmailsArray) { %>
<p>
<%= group.date %>
<% for(let item of group.emails) { %>
<%= item.email %>
<% } %>
</p>
<% } %>
</div>
</div>
这应该会产生您正在寻找的结果。
这是数组:
const emails = [
{ email: 'w@w', createdAt: 2022-03-31T17:07:36.675+00:00 },
{ email: 'a@a', createdAt: 2022-03-31T17:07:36.675+00:00 },
{ email: 'w@b', createdAt: 2022-04-31T17:07:36.675+00:00 },
{ email: 'w@c', createdAt: 2022-04-31T17:07:36.675+00:00 },
{ email: 'w@d', createdAt: 2022-06-31T17:07:36.675+00:00 },
]
我想在ejs中这样格式化:
<div class='card'>
<h3>Unique Date</h3>
<div class='emails'>
<p>All the emails of that unique date</p>
</div>
</div>
我该怎么做?
在后端,您需要使用 reduce 和 map 对现有数组进行分组以执行以下操作。
// Group emails by date
const groupedEmails = emails.reduce((acc, curr) => {
const date = curr.createdAt.split('T')[0];
if (!acc[date]) {
acc[date] = [];
}
acc[date].push(curr);
return acc;
}, {});
// Loop through grouped emails
const groupedEmailsArray = Object.keys(groupedEmails).map(key => {
return {
date: key,
// Sort emails by email in alphabetical order
emails: groupedEmails[key].sort((a, b) => {
if (a.email < b.email) {
return -1;
}
if (a.email > b.email) {
return 1;
}
return 0;
})
}
});
然后您将希望将 groupedEmailArray
传递给您的视图并像这样呈现视图
<div class='card'>
<h3>Unique Date</h3>
<div class='emails'>
<p>All the emails of that unique date</p>
<% for(let group of groupedEmailsArray) { %>
<p>
<%= group.date %>
<% for(let item of group.emails) { %>
<%= item.email %>
<% } %>
</p>
<% } %>
</div>
</div>
这应该会产生您正在寻找的结果。