0

I have a function that takes an object, re-sorts the days manually, and converts a string to an array

export const convertHoursOfOperation = (service) => {
  const hours = {
    Monday: service.hours_of_operation["monday"],
    Tuesday: service.hours_of_operation["tuesday"],
    Wednesday: service.hours_of_operation["wednesday"],
    Thursday: service.hours_of_operation["thursday"],
    Friday: service.hours_of_operation["friday"],
    Saturday: service.hours_of_operation["saturday"],
    Sunday: service.hours_of_operation["sunday"]
  };

  for (let hour in hours) {
    hours[hour] !== null ? hours[hour] = hours[hour].split(",") : hours[hour] = 'Closed'

    hours[hour] !== 'Closed' ? hours[hour].forEach((h) => moment(h, "HH:mm").format('h:mm')) : null
  }

  return hours;
}

output from hours[hour] !== null ? hours[hour] = hours[hour].split(",") : hours[hour] = 'Closed'

monday: '09:00, 15:00' => monday: [09:00, 15:00] OR monday: null => monday: 'Closed'

then I am trying to loop through the array if it is an array and convert the values from military to standard time using moment.

so now my desired output should be:

monday: [09:00, 15:00] => monday: [9:00, 3:00]

currently the line hours[hour] !== 'Closed' ? hours[hour].forEach((h) => moment(h, "HH:mm").format('h:mm')) : null is not converting anything. What am I doing wrong here?

4
  • You don't appear to be setting your moment() to anything. you are simply running the function. Try like the line above it: hours[hour] !== 'Closed' ? hours[hour].forEach((h) => hours[hour] = moment(h, "HH:mm").format('h:mm')) : null; Commented Mar 25, 2022 at 16:30
  • At this point anything that is not 'closed' returns undefined Commented Mar 25, 2022 at 16:35
  • Where is it returning that? Commented Mar 25, 2022 at 16:37
  • @Aditya that has worked! You may submit as answer if you'd like Commented Mar 25, 2022 at 16:41

1 Answer 1

1

you are not setting your moment() to anything. Set the value at that particular index. The correct code should be this:

hours[hour] !== 'Closed' ? hours[hour].forEach((h,index) => hours[hour][index] = moment(h, "HH:mm").format('h:mm')) : null;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.