How to Sort JavaScript Object by Key
In this JavaScript tutorial, you will read and learn information about a functional method of sorting an object by key supported by all major browsers.
In this tutorial, we will share a very simple and functional method to sort an object by key.
Here is an ES5 functional method of sorting. Object.keys gives a list of keys in the provided object, then you should sort those using the default sorting algorithm, after which the reduce() method converts that array back into an object with all of the keys sorted:
Javascript sort object by key
function sortObj(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}Example:
Javascript sort object by key
A one-liner code piece of the above example:
Javascript sort object by key
const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {})Example:
Javascript sort object by key
This behaviour is available in all major browsers and has been standardized in ES5.
Object.keys()
<kbd class="highlighted">Object.keys()</kbd> returns an array of strings corresponding to the enumerable properties found upon the object. The order of the keys is the same as that given by looping over the object's properties manually. <kbd class="highlighted">Object.keys()</kbd> is used to return enumerable properties of a simple object, an array, or an array-like object.