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' }
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' }
here is the 1 liner
Underscore version:
If you don't trust your browser for keeping the order of the keys, I strongly suggest to rely on a ordered array of key-value paired arrays.
Use this code if you have nested objects or if you have nested array obj.
There's a great project by @sindresorhus called sort-keys that works awesome.
You can check its source code here:
https://github.com/sindresorhus/sort-keys
Or you can use it with npm:
Here are also code examples from his readme
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:
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:
Use
var
instead ofconst
for compatibility with ES5 engines.