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

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

    I would add this as a comment to @prototype's post, but my rep isn't high enough.

    If anyone needs a version of orderKeys that @prototype wrote that is compliant with eslint-config-airbnb:

    /**
     * Returns and modifies the input object so that its keys are returned in sorted
     * order when `Object.keys(obj)` is invoked
     *
     * @param {object} obj The object to have its keys sorted
     *
     * @returns {object} The inputted object with its keys in sorted order
     */
    const orderKeys = (obj) => {
      // Complying with `no-param-reassign`, and JavaScript seems to assign by reference here
      const newObj = obj;
      // Default `.sort()` chained method seems to work for me
      const keys = Object.keys(newObj).sort();
    
      const after = {};
      // Add keys to `after` in sorted order of `obj`'s keys
      keys.forEach((key) => {
        after[key] = newObj[key];
        delete newObj[key];
      });
    
      // Add keys back to `obj` in sorted order
      keys.forEach((key) => {
        newObj[key] = after[key];
      });
    
      return newObj;
    };
    

    Using @prototype's tests:

    const example = { 
      3: 'charlie',
      'p:style': 'c',
      berries: 'e',
      'p:nvSpPr': 'a',
      'p:txBody': 'd',
      apples: 'e',
      5: 'eagle',
      p:spPr: 'b'
    }
    
    const obj = orderKeys(example);
    
    console.log(obj);
    
    console.log(Object.keys(obj));
    

    Outputs the following:

    Babel Compiler v6.4.4
    Copyright (c) 2014-2015 Sebastian McKenzie
    
    { 3: 'charlie',
      5: 'eagle',
      apples: 'e',
      berries: 'e',
      'p:nvSpPr': 'a',
      'p:spPr': 'b',
      'p:style': 'c',
      'p:txBody': 'd' }
    [ '3',
      '5',
      'apples',
      'berries',
      'p:nvSpPr',
      'p:spPr',
      'p:style',
      'p:txBody' ]
    

    For whatever it's worth, I needed this in my React app so that I could sort the options of a dropdown that was based on a state object, assigned after a response from my API.

    Initially I did

    return (
      // ...
      
                            
        
    提交评论

提交回复
热议问题