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' }
Suppose it could be useful in VisualStudio debugger which shows unordered object properties.
Solution:
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):
Note: Object.keys is an ECMAScript 5.1 method but here is a polyfill for older browsers:
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
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.
Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.
Sorts keys recursively while preserving references.
Example:
Maybe a bit more elegant form:
P.S. and the same with ES6+ syntax: