Skip to content

Function: sortObject() ​

sortObject<T>(object, options?): T

Copy a plain object with its keys in alphabetical order, compared with localeCompare (the runtime's default locale: the case does not come first, {b, a, C} gives a, b, C). It is sortKeys with that comparison: the integer-like keys still come first in ascending numeric order, and the same values are copied (the getters and setters as they are).

Type Parameters ​

T ​

T extends Record<string, any>

Parameters ​

object ​

T

A plain object (or an array, copied).

options? ​

SortObjectOptions

Whether the nested objects are sorted, and the order.

Returns ​

T

A new object with the keys sorted.

Throws ​

When object is neither a plain object nor an array.

Example ​

typescript
import {sortObject} from 'lakutata/utils'

console.log(Object.keys(sortObject({b: 1, a: 2, C: 3})))
//['a', 'b', 'C']
console.log(JSON.stringify(sortObject({b: 1, a: {y: 1, x: 2}}, {order: 'desc', deep: true})))
//{"b":1,"a":{"y":1,"x":2}}

Released under the MIT License.