Home > Blockchain >  Looping through multiple arrays and converting values using moment JS
Looping through multiple arrays and converting values using moment JS

Time:03-26

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?

CodePudding user response:

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;
  • Related