
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!
Categories:
Related Articles

Disabling Gatsby Telemetry. 
Object.keys(), Object.values(), and Object.entries() Explained. Object.keys(),Object.values(), andObject.entries()Explained
Mastering JavaScript's slice(). Mastering JavaScript's
slice()
Why We Use an Empty Dependency Array in React's useEffect Hook. Why We Use an Empty Dependency Array in React's
useEffectHook
React's Reconciliation Algorithm Explained. React's Reconciliation Algorithm Explained

Why this Changes in JavaScript Event Handlers and Methods. Why
thisChanges in JavaScript Event Handlers and Methods
Dynamic Array Manipulation with JavaScript's splice(). Dynamic Array Manipulation with JavaScript's
splice()
Using the CSS :has Pseudo‑Class. Using the CSS
:hasPseudo‑Class
3Sum Closest in JavaScript: Sorting and Two Pointers. 3Sum Closest in JavaScript: Sorting and Two Pointers
Where to Find Jobs in Web Development. Where to Find Jobs in Web Development

Object Equality in JavaScript: {} isn't Equal to {}. Object Equality in JavaScript:
{}isn't Equal to{}
Static Methods vs. Instance Methods in JavaScript Classes. Static Methods vs. Instance Methods in JavaScript Classes