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' }
To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.
Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works. The result will automatically sort and display in the output text area.
Array. sort() function sorts an Array. The Sort() function will sort array using the optional compareFunction provided, if it is not provided Javascript will sort the array object by converting values to strings and comparing strings in UTF-16 code units order.
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:
- First all Array indices, sorted numerically.
- Then all string keys (that are not indices), in the order in which they were created.
- 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().reduce( (obj, key) => { obj[key] = unordered[key]; return obj; }, {} ); console.log(JSON.stringify(ordered)); // → '{"a":"baz","b":"foo","c":"bar"}'
Use var
instead of const
for compatibility with ES5 engines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With