Sort the Keys of an Object with JavaScript

As you probably know, an object in JavaScript is an unordered collection of key‑value pairs. However, in certain situations, you may find that you need to sort the keys of an object alphabetically or numerically.
This can be achieved fairly easily by:
- Getting an array of the object's keys;
- Sorting them;
- Using
reduce()to rebuild the object, in the order of the keys.
For example:
const sortObject = obj => { // get the keys of the object var keys = Object.keys(obj); // sort the keys keys.sort(); // use reduce to rebuild the object return keys.reduce((sortedObj, key) => { sortedObj[key] = obj[key]; return sortedObj; }, {});};You could use this function like this:
let myObj = { c: 1, a: 2, b: 3 };console.log(sortObject(myObj));//=> {a: 2, b: 3, c: 1}Do bear in mind that this method will create a new object, rather than modifying the original one.
Also, If you want to sort the object numerically, you would need to pass a function as a parameter to the sort method like this:
keys.sort((a, b) => { return a - b;});Easy!