Is there a way to sort/order keys in JavaScript objects?

后端 未结 7 2103
故里飘歌
故里飘歌 2020-11-28 08:16

For example the following

var data = {
    \'States\': [\'NSW\', \'VIC\'],
    \'Countries\': [\'GBR\', \'AUS\'],
    \'Capitals\': [\'SYD\', \'MEL\']
}
for          


        
相关标签:
7条回答
  • 2020-11-28 09:09

    You can also sort it in this way.

    const data = {
      States: ['NSW', 'VIC'],
      Countries: ['GBR', 'AUS'],
      Capitals: ['SYD', 'MEL']
    }
    
    const sortedObject = Object.fromEntries(Object.entries(data).sort())
    

    I cannot explain in detail why it works but apparently it's working flawlessly :) Try yourself if you're not believing me :D

    Note that your browser or Node.js version should support Object.fromEntries

    For browser compatibility check bottom of this page

    For Node, it will work for versions from 12 and higher. For Deno from the v1.

    0 讨论(0)
提交回复
热议问题