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

后端 未结 7 2172
故里飘歌
故里飘歌 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:01

    Here's a one-liner to sort an object's keys using lodash

    _.chain(obj).toPairs().sortBy(0).fromPairs().value()
    

    With your example data:

    var data = {
        'States': ['NSW', 'VIC'],
        'Countries': ['GBR', 'AUS'],
        'Capitals': ['SYD', 'MEL']
    }
    data = _.chain(data)
      .toPairs() // turn the object into an array of [key, value] pairs
      .sortBy(0) // sort these pairs by index [0] which is [key]
      .fromPairs() // convert array of pairs back into an object {key: value}
      .value() // return value
    /*
    {
      Capitals: [ 'SYD', 'MEL' ],
      Countries: [ 'GBR', 'AUS' ],
      States: [ 'NSW', 'VIC' ]
    }
    */
    
    

提交回复
热议问题