Home > Net >  how to write out entire months with object key where the months are in numbers
how to write out entire months with object key where the months are in numbers

Time:07-07

Currently I'm slightly confused why my code is not working as intended, and I was hoping you guys would be able to help me.

I have an object with year and months.

chosenMonths = {[
    2022: [0,1,2]
    2018: [9,10]
    2017: [11]
]}

I have a function that will convert the number into written out months:

const writeOutMonth = function(num, locale) {
    const date = new Date();
    date.setMonth(num);

    return date.toLocaleString(locale, {month: 'long',});
}

And inside my code I have an Object.keys where I want to print out the year and then the written out months on the page.

${Object.keys(chosenMonths).reverse().map((year) => html`<p1> ${year}: ${writeOutMonth(chosenMonth[year].sort().join(', '), 'en-gb')}</p>`)} 

Right now, I see it will render:

2022: Invalid Date
2021: Invalid Date
2017: December

My question is: why is it Invalid Date, when I have multiple numbers in a year, and how do I make it work?

CodePudding user response:

I had to made modifications to make the code run, I believe that's what you need, the problem was that you were passing a string composed of months, instead of passing a month, I change the method to receive an array og months, also, to the sort() I had to the add the sorting function

chosenMonths = {
  2022: [0, 1, 2],
  2018: [9, 10],
  2017: [11],
};

const writeOutMonth = function (monthArray, locale) {
  let monthNames = [];

  monthArray.forEach((mon) => {
    const date = new Date();
    date.setMonth(mon);
    monthNames.push(date.toLocaleString(locale, { month: "long" }));
  });

  return monthNames.join(", ");
};

let result = Object.keys(chosenMonths)
  .reverse()
  .map(
    (year) =>
      `<p1> ${year}: ${writeOutMonth(
        chosenMonths[year].sort((a, b) => a - b),
        "en-gb"
      )}</p>`
  );

console.log(result);
  • Related