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' }
A lot of people have mention that "objects cannot be sorted", but after that they are giving you a solution which works. Paradox, isn't it?
No one mention why those solutions are working. They are, because in most of the browser's implementations values in objects are stored in the order in which they were added. That's why if you create new object from sorted list of keys it's returning an expected result.
And I think that we could add one more solution – ES5 functional way:
ES2015 version of above (formatted to "one-liner"):
Short explanation of above examples (as asked in comments):
Object.keys
is giving us a list of keys in provided object (obj
oro
), then we're sorting those using default sorting algorithm, next.reduce
is used to convert that array back into an object, but this time with all of the keys sorted.Here is a clean lodash-based version that works with nested objects
It would be even cleaner if lodash had a
toObject()
method...Using lodash this will work:
Just food for thought.
This works for me
Pure JavaScript answer to sort an Object. This is the only answer that I know of that will handle negative numbers. This function is for sorting numerical Objects.
Input obj = {1000: {}, -1200: {}, 10000: {}, 200: {}};
The output will be an object sorted by those numbers with new keys starting at 0.
This is an old question, but taking the cue from Mathias Bynens' answer, I've made a short version to sort the current object, without much overhead.
after the code execution, the "unordered" object itself will have the keys alphabetically sorted.