Sort the Keys of an Object with JavaScript

JavaScript objects store key‑value pairs, but their keys do not follow an arbitrary order. For ordinary string keys, rebuilding an object in a chosen order can make output easier to read. Array‑index keys have their own ordering rule, though, so this is not a general‑purpose way to store a sorted sequence.
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!
Postscript
June 2026: For an ordinary object, array‑index keys come first in ascending numeric order, followed by other string keys in insertion order, then symbol keys in insertion order. Object.keys() includes only own enumerable string keys. Rebuilding keys "10" and "2" in alphabetical order therefore still makes Object.keys() return ["2", "10"]. Use a sorted array of entries, or a Map built from them, when the sequence itself matters. The examples above are useful for simple output normalisation, with that limit in mind.