Skip to content

Instantly share code, notes, and snippets.

@Pomax
Last active October 15, 2021 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pomax/039e731b4109bf36fc6100034fa627de to your computer and use it in GitHub Desktop.
Save Pomax/039e731b4109bf36fc6100034fa627de to your computer and use it in GitHub Desktop.
/**
* This is a function for use with JSON.stringify(input, sortedObjectKeys, number)
* that ensures that object keys are sorted in alphanumerical order.
*/
export function sortedObjectKeys(_, data) {
// Ignore primitives.
if (data === null) return null;
if (typeof data !== "object") return data;
// Also ignore iterables, which are type "object" but should not be sorted.
if (data.__proto__[Symbol.iterator]) return data;
// Then sort the object keys and yield a new object with that
// ordering enforced by key insertion.
return Object.fromEntries(Object.entries(data).sort());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment