這是陣列:
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>
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
在您的后端,您將希望使用 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>
這應該會產生您正在尋找的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/454361.html
標籤:javascript 数组 目的 ejs
