Hello I have an object that I want to browse and when a value is equal to true I fill an array. My code works but I don’t think it’s good to put so much if.
daysOfWeek: {
lundi: true,
mardi: true,
mercredi: true,
jeudi: false,
vendredi: true,
samedi: true,
dimanche: true
}
let days = []
if (daysOfWeek != null) {
if (daysOfWeek.lundi === true) {
days.push(2)
}
if (daysOfWeek.mardi === true) {
days.push(3)
}
if (daysOfWeek.mercredi === true) {
days.push(4)
}
if (daysOfWeek.jeudi === true) {
days.push(5)
}
if (daysOfWeek.vendredi === true) {
days.push(6)
}
if (daysOfWeek.samedi === true) {
days.push(7)
}
if (daysOfWeek.dimanche === true) {
days.push(1)
}
}
return days
days = [2,3,4,6,7,1]
I tried the switch/case but it doesn’t work for conditions.
Does anyone have another solution for me to explore?
I agree with this answer suggestion.
The number must be from 0
(Sunday) to 6
(Saturday).
In some locales, it may be 0
(Monday) to 6
(Sunday).
But if you want to set 1
as the first day of the week, I would suggest the code below
const daysOfWeek = {
lundi: true,
mardi: true,
mercredi: true,
jeudi: false,
vendredi: true,
samedi: true,
dimanche: true
}
const TOTAL_DAYS_OF_WEEK = 7;
const IS_SUNDAY_A_FIRST_DAY_OF_WEEK = true;
const FIRST_DAY_START_WITH = 1;
const result = [];
Object.values(daysOfWeek).forEach((value, index) => {
if(value) {
const dayOfWeek = (index + IS_SUNDAY_A_FIRST_DAY_OF_WEEK) % TOTAL_DAYS_OF_WEEK + FIRST_DAY_START_WITH;
result.push(dayOfWeek);
}
});
console.log(result)