Sort JavaScript object by key

vdh_ant picture vdh_ant · Mar 29, 2011 · Viewed 598k times · Source

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' }

Answer

Mathias Bynens picture Mathias Bynens · Jun 28, 2015

The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6/ES2015 spec has been published.


See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:

All methods that iterate over property keys do so in the same order:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. Then all symbols, in the order in which they were created.

So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.

Here’s how you can sort an object by its keys/properties, alphabetically:

const unordered = {
  'b': 'foo',
  'c': 'bar',
  'a': 'baz'
};

console.log(JSON.stringify(unordered));
// → '{"b":"foo","c":"bar","a":"baz"}'

const ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
  ordered[key] = unordered[key];
});

console.log(JSON.stringify(ordered));
// → '{"a":"baz","b":"foo","c":"bar"}'

Use var instead of const for compatibility with ES5 engines.