skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. The issue you are experiencing with the keys in your string object being converted to numbers could be related to how JavaScript handles object keys. By default, JavaScript treats object keys as strings, but when they are purely numeric, they can also be interpreted as numbers.

    To ensure consistent ordering and prevent the automatic conversion of keys to numbers, you can try using an array of objects instead of an object with string keys. Here’s an example:

    export const HOURS = [
      { value: '00', label: '00' },
      { value: '01', label: '01' },
      { value: '02', label: '02' },
      // ... rest of the values
    ];
    

    Then, in your select box, you can map over the array to generate the options:

    <select>
      {HOURS.map((hour) => (
        <option key={hour.value} value={hour.value}>
          {hour.label}
        </option>
      ))}
    </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search