I have an object which looks as so:
const hours = {
Monday: ['9:00 am', '4:00 pm'],
Tuesday: ['9:00 am', '4:00 pm'],
Wednesday:['9:00 am', '3:00 pm']
Thursday: ['9:00 am', '3:00 pm'],
Friday: ['9:00 am', '3:00 pm'],
Saturday: "Closed",
Sunday: "Closed",
}
I then get the current day of the week in a string format:
const d = new Date();
let day = d.getDay();
const daysOfWeek = {
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday'
}
const currentDayString = daysOfWeek[day]
I now need to create a new object that has the current day, up until sunday.
ex output
if the day is 'Friday' the hours obj should be:
{
Friday: ['9:00 am', '3:00 pm'],
Saturday: "Closed",
Sunday: "Closed"
}
How can I achieve this?
Let today's day be d (ex: 'Monday', 'Tuesday') then, and serverData be data we are getting from server so,
let found=0;
let result={}
Object.keys(daysOfWeek).forEach(key => {
if (found) {
result[daysOfWeek[key]] = serverData[daysOfWeek[key]]
};
if (daysOfWeek[key] === d) {
found = 1;
}
})
Let say your starting day is "thursday", your result object could never be like this :
{
Thursday: (2) ['9:00 am', '3:00 pm'
Friday: (2) ['9:00 am', '3:00 pm']
Saturday: "Closed"
Sunday: "Closed"
}
Cause JS orders an object alphabetically.
Try to push your results into an array like this (data been your server data):
let result = [];
for(let i=day; i <= Object.keys(daysOfWeek).length; i++)
{
// result[daysOfWeek[i]] = data[daysOfWeek[i]]; // return object
result.push(data[daysOfWeek[i]]); // return array
}
Can be done with reduce
const data = {
Monday: ['9:00 am', '4:00 pm'],
Tuesday: ['9:00 am', '4:00 pm'],
Wednesday: ['9:00 am', '3:00 pm'],
Thursday: ['9:00 am', '3:00 pm'],
Friday: ['9:00 am', '3:00 pm'],
Saturday: 'Closed',
Sunday: 'Closed',
};
const day = new Date().toLocaleString('en', { weekday: 'long' });
const result = Object.entries(data).reduce((prev, [key, value]) => {
if (key === day || day in prev) {
prev[key] = value;
}
return prev;
}, {});
console.log(result);