Sort JavaScript object by key

2018-12-31 00:50发布

I need to sort JavaScript objects by key.

Hence the following:

{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }

Would become:

{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }

24条回答
栀子花@的思念
2楼-- · 2018-12-31 01:32

Suppose it could be useful in VisualStudio debugger which shows unordered object properties.

(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})({b:2,a:1,c:3})
查看更多
春风洒进眼中
3楼-- · 2018-12-31 01:32

Solution:

function getSortedObject(object) {
  var sortedObject = {};

  var keys = Object.keys(object);
  keys.sort();

  for (var i = 0, size = keys.length; i < size; i++) {
    key = keys[i];
    value = object[key];
    sortedObject[key] = value;
  }

  return sortedObject;
}

// Test run
getSortedObject({d: 4, a: 1, b: 2, c: 3});

Explanation:

Many JavaScript runtimes store values inside an object in the order in which they are added.

To sort the properties of an object by their keys you can make use of the Object.keys function which will return an array of keys. The array of keys can then be sorted by the Array.prototype.sort() method which sorts the elements of an array in place (no need to assign them to a new variable).

Once the keys are sorted you can start using them one-by-one to access the contents of the old object to fill a new object (which is now sorted).

Below is an example of the procedure (you can test it in your targeted browsers):

/**
 * Returns a copy of an object, which is ordered by the keys of the original object.
 *
 * @param {Object} object - The original object.
 * @returns {Object} Copy of the original object sorted by keys.
 */
function getSortedObject(object) {
  // New object which will be returned with sorted keys
  var sortedObject = {};

  // Get array of keys from the old/current object
  var keys = Object.keys(object);
  // Sort keys (in place)
  keys.sort();

  // Use sorted keys to copy values from old object to the new one
  for (var i = 0, size = keys.length; i < size; i++) {
    key = keys[i];
    value = object[key];
    sortedObject[key] = value;
  }

  // Return the new object
  return sortedObject;
}

/**
 * Test run
 */
var unsortedObject = {
  d: 4,
  a: 1,
  b: 2,
  c: 3
};

var sortedObject = getSortedObject(unsortedObject);

for (var key in sortedObject) {
  var text = "Key: " + key + ", Value: " + sortedObject[key];
  var paragraph = document.createElement('p');
  paragraph.textContent = text;
  document.body.appendChild(paragraph);
}

Note: Object.keys is an ECMAScript 5.1 method but here is a polyfill for older browsers:

if (!Object.keys) {
  Object.keys = function (object) {
    var key = [];
    var property = undefined;
    for (property in object) {
      if (Object.prototype.hasOwnProperty.call(object, property)) {
        key.push(property);
      }
    }
    return key;
  };
}
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 01:35

Just use lodash to unzip map and sortBy first value of pair and zip again it will return sorted key.

If you want sortby value change pair index to 1 instead of 0

var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
console.log(_(o).toPairs().sortBy(0).fromPairs().value())

enter image description here

查看更多
明月照影归
5楼-- · 2018-12-31 01:35

Simple and readable snippet, using lodash.

You need to put the key in quotes only when calling sortBy. It doesn't have to be in quotes in the data itself.

_.sortBy(myObj, "key")

Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.

_.map( _.sortBy(myObj, "key") , "value");
查看更多
怪性笑人.
6楼-- · 2018-12-31 01:35

Sorts keys recursively while preserving references.

function sortKeys(o){
    if(o && o.constructor === Array)
        o.forEach(i=>sortKeys(i));
    else if(o && o.constructor === Object)
        Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
            sortKeys(e[1]);
            delete o[e[0]];
            o[e[0]] = e[1];
        });
}

Example:

let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}
查看更多
有味是清欢
7楼-- · 2018-12-31 01:37

Maybe a bit more elegant form:

 /**
     * Sorts a key-value object by key, maintaining key to data correlations.
     * @param {Object} src  key-value object
     * @returns {Object}
     */
var ksort = function ( src ) {
      var keys = Object.keys( src ),
          target = {};
      keys.sort();
      keys.forEach(function ( key ) {
        target[ key ] = src[ key ];
      });
      return target;
    };


// Usage
console.log(ksort({
  a:1,
  c:3,
  b:2  
}));

P.S. and the same with ES6+ syntax:

function ksort( src ) {
  const keys = Object.keys( src );
  keys.sort();
  return keys.reduce(( target, key ) => {
        target[ key ] = src[ key ];
        return target;
  }, {});
};
查看更多
登录 后发表回答