How to Sort JavaScript Object by Key
In this tutorial, we will share a very simple and functional method to sort an array of objects by key.
Here is a ES5 functional method of sorting. The Object.keys gives a list of keys in provided object, then you should sort those using default sorting algorithm, after which the reduce() method converts that array back into an object with all of the keys sorted:
function sortObj(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}
Example:
A one-liner code piece of the above example:
const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {})
Example:
Object.keys()
Object.keys() returns an array where elements are strings corresponding to the enumerable properties found upon the object. The order of the property is similar to that given by the object manually in a loop applied to the properties. Object.keys() is used to return enumerable properties of a simple array, of an array-like an object, and an array-like object with random ordering.