3

In next.js app,

I'm using an object of string key and string value in the select box which looks like this:

export const HOURS: { [key: string]: string } = {
  '00': '00',
  '01': '01',
  '02': '02',
  '03': '03',
  '04': '04',
  '05': '05',
  '06': '06',
  '07': '07',
  '08': '08',
  '09': '09',
  '10': '10',
  '11': '11',
  '12': '12',
  '13': '13',
  '14': '14',
  '15': '15',
  '16': '16',
  '17': '17',
  '18': '18',
  '19': '19',
  '20': '20',
  '21': '21',
  '22': '22',
  '23': '23',
} as const

when I debug it in the local running app, it's just fine (it prints out the object as it was defined)

but in a bundled & deployed application, the key of the object is automatically converted as number, which makes the sorted order of the select box different from the desired output. ('00' becomes 0 and '01' becomes 1 so the order is not same comparing it to the local application)

0: "00",
1: "01",
2: "02"
...

is there any way to fix it and preserve the key as it is declared?

i tried defining types { [key: string]: string } and declaring as as const but not working

juliomalves
  • 42,130
  • 20
  • 150
  • 146

1 Answers1

0

First of all, you should not rely on object sorting order, it is not guaranteed. Better to use Map for this. It will solve your problem.

If to go further: I saw that you named your object HOURS and could assume that you are working with time. And the real goal of your object is only to add zero to single digit value. There are multiple other ways to set time format depending on your particular implementation and date formatting syntax. Or primitive way here Javascript change getHours to 2 digit or here https://bobbyhadz.com/blog/javascript-get-minutes-with-leading-zero

Dmitriy Sakhno
  • 453
  • 3
  • 8