Skip to content

Function: sortKeys() ​

sortKeys(object, options?): any

Copy a plain object with its keys in sorted order, for a stable serialization (a JSON hash, a cache key, a diff). The integer-like keys ('1', '20') always come first in ascending numeric order, whatever compare: JavaScript orders them so. Only the own enumerable string keys are kept, with their attributes (writable, configurable); the values are not copied, except the nested objects and arrays rebuilt by deep, and the getters and setters are copied as they are, not called (a getter's object is not sorted by deep). A circular reference is kept as a reference to the copy.

Parameters ​

object ​

any

A plain object (an object literal, Object.create(null)), or an array (copied, its items sorted when deep).

options? ​

SortKeysOptions

Whether the nested objects are sorted, and the comparison of the keys.

Returns ​

any

A new object (or array) with the keys sorted.

Throws ​

When object is neither a plain object nor an array (a class instance, a Map, a primitive).

Example ​

typescript
import {sortKeys} from 'lakutata/utils'

const sorted: Record<string, any> = sortKeys({b: 1, a: {d: 1, c: 2}}, {deep: true})
console.log(JSON.stringify(sorted))
//{"a":{"c":2,"d":1},"b":1}

Released under the MIT License.