在多个foreach方法中编写多个切换用例的更好方法



我正在尝试制作一个网络应用程序,人们可以在其中将锻炼添加到一周中某一天的日常活动中,它将在一个页面上显示他们的整个日常活动。我还希望将练习的名称链接到相应的页面。例如,我的数据在mongodb中是这样的:

_id:60e2edf7014df85fd8b6e073
routineName:"test"
routineUsername: "tester"
monday:[{
_id: 60e430d45395d73bf41c7be8
exercise: "Bicep curls"
}{
_id: 60e4329592e3fa445836d983
exercise: "Overhead press"
}]
tuesday:[{
_id:60e2ee8962c0c15840ecc69b
exercise:"Hanging leg raise"
}] 
..etc

我在EJS:中有这个

<% routine.monday.forEach(monday => { %>
<ul>
<% switch (monday.exercise) {
case 'Hanging leg raise' : %>
<a href="/muscles/abs/hanginglegraise"><li><%= monday.exercise %></li></a>
<% break;

case 'Bicep curls' : %>
<a href="/muscles/biceps/bicepcurls"><li><%= monday.exercise %></li></a>
<% break;

case 'Calf raises' : %>
<a href="/muscles/calves/calfraises"><li><%= monday.exercise %></li></a>
<% break;
case 'Barbell bench press' : %>
<a href="/muscles/chest/barbellbenchpress"><li><%= monday.exercise %></li></a>
<% break;
case 'Incline bench press' : %>
<a href="/muscles/chest/inclinebenchpress"><li><%= monday.exercise %></li></a>
<% break;
case 'Overhead press' : %>
<a href="/muscles/frontdeltoids/overheadpress"><li><%= monday.exercise %></li></a>
<% break;
case 'Barbell squat' : %>
<a href="/muscles/quadriceps/barbellsquat"><li><%= monday.exercise %></li></a>
<% break;
case 'Shrugs' : %>
<a href="/muscles/trapezius/shrugs"><li><%= monday.exercise %></li></a>
<% break;
} %>
</ul>
<% }) %>
..etc

但正如你所看到的,我必须在一周中的每一天重复这个代码7次,每次都使用switch case,这样我就可以让练习转到正确的链接。我觉得这是一种糟糕而低效的方法,但我不知道/想不出更好的方法,任何帮助都将不胜感激。

一个好的做法是使用对象。可以调用类似foo.barfoo['bar']的对象。因此,首先创建一个对象,如:

const exercices = {
'Hanging leg raise': <a href="/muscles/abs/hanginglegraise"><li></a>
// Fill with the rest
...
}
routine.monday.forEach(monday => { %>
<ul>
exercices[monday.exercice]
</ul>
} %>

使用这种设计模式为您的需求奠定了基础。

routine.monday.forEach(monday => { %>
<ul>
<a href=`/muscles/abs/${monday.exercice.trim()}`><li><%= monday.exercise %></li></a>
</ul>
} %>

最新更新