skip to Main Content

I have an object

 let files = {
            '00':{},
            '01':{},
            '02':{},
            '03':{},
            '04':{},
            '05':{},
            '06':{},
            '07':{},
            '08':{},
            '09':{},
            '10':{},
            '11':{},
            '12':{},
            '13':{},
            '14':{},
            '15':{}
        }

console.log(Object.keys(files))

the result I’m getting is this.

["10","11","12","13","14","15","00","01","02","03","04","05","06","07","08","09"]

1. why it’s reading key from 10 not from 00 ?
2. How to make it read from zero i.e first key of an object ?

2

Answers


  1. This is because of the order of execution of Object Keys in JS:

    Numbers -> Strings -> Symbols

    And in case of Strings, JS checks if they can be converted to Numbers.

    Eg: "10" can be converted to 10, but "00" can’t be.

    That’s why you see ["10","11","12","13","14","15","00","01","02","03","04","05","06","07","08","09"]

    References:

    1. https://dev.to/frehner/the-order-of-js-object-keys-458d
    2. https://www.stefanjudis.com/today-i-learned/property-order-is-predictable-in-javascript-objects-since-es2015/
    Login or Signup to reply.
  2. JavaScript object properties have a strict pre-defined order, which you cannot change. The obvious fix would be to use an Array instead, because arrays are designed to handle a custom order, unlike objects. If this is not an option for you, the only way is to sort the array returned by Object.keys():

    const files = {
      '00': {},
      '01': {},
      '02': {},
      '03': {},
      '04': {},
      '05': {},
      '06': {},
      '07': {},
      '08': {},
      '09': {},
      '10': {},
      '11': {},
      '12': {},
      '13': {},
      '14': {},
      '15': {},
    };
    
    console.log(Object.keys(files).sort());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search