How to Sort the Keys of an Object in JavaScript
A common data presentation task is to display the properties of an object in alphabetical order. However, it's crucial to understand that standard JavaScript objects do not guarantee key order. While modern JavaScript engines do often preserve the insertion order of keys, you should never rely on this for sorting.
To reliably sort an object's keys, you must convert the object to an array, sort the array, and then create a new object from the sorted result. This guide will demonstrate the modern and recommended best practice for this task using Object.keys(), sort(), and Object.fromEntries().
The Core Problem: Object Key Order is Not Guaranteed
Unlike a Map, a plain JavaScript object is not designed to maintain a specific order for its keys. While console.log() might display keys in a certain order, you cannot and should not write code that depends on this behavior. To guarantee a sorted order, you must create a new, sorted object.
Problem: you have an object with keys in an arbitrary order, and you need a new object where the keys are sorted alphabetically.
// Problem: Create a new object with keys sorted alphabetically ('a', 'b', 'z').
let unsortedObj = {
zulu: 3,
alpha: 1,
charlie: 2
};
The Core Method (Recommended): Object.keys(), sort(), and Object.fromEntries()
This modern, declarative approach is the cleanest and most readable way to sort an object's keys.
The logic:
- Get Keys: Get an array of the object's keys using
Object.keys(). - Sort Keys: Sort this array of keys alphabetically using
Array.prototype.sort(). - Reconstruct: Create a new object by iterating over the sorted keys and building a new object. The
Object.fromEntries()method is perfect for this.
Solution:
function sortObjectKeys(obj) {
// 1. Get and sort the keys
let sortedKeys = Object.keys(obj).sort();
// 2. Create a new array of [key, value] pairs in the sorted order
let sortedEntries = sortedKeys.map(key => [key, obj[key]]);
// 3. Convert the array of entries back into an object
return Object.fromEntries(sortedEntries);
}
// Example Usage:
let unsortedObj = { zulu: 3, alpha: 1, charlie: 2 };
let sortedObj = sortObjectKeys(unsortedObj);
console.log(sortedObj);
Output:
{alpha: 1, charlie: 2, zulu: 3}
How the Sorting Process Works
Let's break down the sortObjectKeys function step-by-step.
Step 1: Get and Sort the Keys
Object.keys(obj) returns an array of the object's property names. We then call .sort() on this array to sort them alphabetically.
let unsortedObj = { zulu: 3, alpha: 1, charlie: 2 };
let sortedKeys = Object.keys(unsortedObj).sort();
console.log(sortedKeys);
Output:
['alpha', 'charlie', 'zulu']
Step 2: Create Sorted Entries
We use map() to transform our sortedKeys array into an array of [key, value] pairs, which is the format Object.fromEntries() expects.
let sortedEntries = sortedKeys.map(key => [key, unsortedObj[key]]);
console.log(sortedEntries);
Output:
[ ['alpha', 1], ['charlie', 2], ['zulu', 3] ]
Step 3: Reconstruct the Object
Object.fromEntries() takes an array of [key, value] pairs and creates a new object from them. Since our array is sorted, the new object is constructed in that order.
let finalObject = Object.fromEntries(sortedEntries);
console.log(finalObject);
Output:
{ alpha: 1, charlie: 2, zulu: 3 }
An Alternative Method: Using reduce()
A more traditional functional approach is to use Array.prototype.reduce() to build the new object. This is also a valid method, though it can be less readable for developers unfamiliar with reduce.
Solution:
let unsortedObj = { zulu: 3, alpha: 1, charlie: 2 };
let sortedObj = Object.keys(unsortedObj)
.sort()
.reduce((accumulator, key) => {
accumulator[key] = unsortedObj[key];
return accumulator;
}, {}); // Start with an empty object as the accumulator
console.log(sortedObj);
Output:
{ alpha: 1, charlie: 2, zulu: 3 }
This method iterates over the sorted keys and progressively builds up the new object.
Conclusion
While JavaScript objects do not have a guaranteed key order, you can easily create a new object with sorted keys for display or processing.
- The recommended best practice is to get the keys with
Object.keys(), sort them with.sort(), and then reconstruct a new object, preferably usingObject.fromEntries(). - This approach is non-mutating; it creates a new object and leaves the original object unchanged.
- Remember that even though the new object is created in a sorted order, you should not write subsequent code that relies on this order being preserved during further operations. If you need a guaranteed order, use a
Mapobject instead.