Sort the Keys of an Object with JavaScript

Abstract image used to represent Sort the Keys of an Object with JavaScript
Image by Samantha Lam.

JavaScript objects store keyvalue 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. Arrayindex keys have their own ordering rule, though, so this is not a generalpurpose way to store a sorted sequence.

This can be achieved fairly easily by:

  1. Getting an array of the object's keys;
  2. Sorting them;
  3. 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, arrayindex 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.

Have a complex web platform issue?

Tell me what is blocked, what has changed, and what needs to be true after the fix. I'll come back with a practical next step.