Skip to content

sortKeys

Creates a new object with the same entries as the input, but with its own keys sorted. Shallow only — nested objects are copied as-is, their keys are not re-sorted. Key order matters for things like JSON.stringify diffs and snapshot stability; this does not change equality ({a:1,b:2} and {b:2,a:1} are already equal), just iteration/serialization order. Note: integer-index-like keys ("0", "1", "42"…) are always iterated first, in numeric order, by the JS engine itself — no object key ordering can override that language behavior. A prototype-polluting key (__proto__, constructor, prototype) is silently skipped, same as the rest of @helpers4/object.

Available since v3.0.3

import { sortKeys } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { sortKeys } from 'helpers4/object';
sortKeys<T extends Record<string, unknown>>(obj: T, compareFn?: function): T
ParameterTypeDescription
objTThe object whose keys to sort
compareFnfunctionOptional custom comparator, passed directly to `Array.prototype.sort` (optional)

T — A new object with the same entries, own keys in sorted order

Useful for stable JSON.stringify output or predictable snapshot tests.

sortKeys({ b: 2, a: 1, c: 3 })
// => { a: 1, b: 2, c: 3 }

View source on GitHub