sort-object-properties
Utility that return copy of object with sorted keys
Installation
npm install sort-object-properties --save
Usage
Import
//ES6;//CommonJSvar sort = ;
Simple call
const objectWithUnsortedKeys = d: 'value1' c: 'value2' e: 'value3' b: 'value4' a: 'value5'; var sortedObject = ; console; /* a: 'value5', b: 'value4', c: 'value2', d: 'value1', e: 'value3'*/
API
Global function
By default sorts object ascending by its keys. Use second parameter if need more flexibility.
Argument | Type | Optional | Description |
---|---|---|---|
obj | Object |
false | Object to sort |
sortFunction | SortFunction |
true | Function used to sort object |
SortFunction
Argument | Type | Optional | Description |
---|---|---|---|
a | PropertyObject |
true | Left side property |
b | PropertyObject |
true | Right side property |
PropertyObject
Property | Type | Optional | Description |
---|---|---|---|
key | string , number , Symbol |
true | Key used in parent object |
value | any |
true | Value assigned to key |
value function
Sorts object properties by its values.
Argument | Type | Optional | Description |
---|---|---|---|
obj | Object |
false | Object to sort |
direction | SortDirection , Number |
true | Sort direction |
valueSelector | Function |
true | Function that return simple value from complex type properties |
key function
Sorts object properties by its keys.
Argument | Type | Optional | Description |
---|---|---|---|
obj | PropertyObject |
false | Object to sort |
direction | SortDirection , Number |
true | Sort direction |
sortDirection constant
Constant with sort directions, use that const or just use plain numbers in function calls.
Name | Value |
---|---|
ascending | 1 |
descending | -1 |
Examples
Sort by values using global function
const objectWithUnsortedValues = key1: 'd' key2: 'a' key3: 'e' key4: 'b' key5: 'c'; //ES6 syntaxvar sortedObject = ;//ES5 syntaxvar sortedObject = ; console;/* key2: 'a', key4: 'b', key5: 'c' key1: 'd', key3: 'e',*/
Sort by values using values function
; const objectWithUnsortedValues = key1: 'd' key2: 'a' key3: 'e' key4: 'b' key5: 'c'; var sortedObject = ; console;/* key2: 'a', key4: 'b', key5: 'c' key1: 'd', key3: 'e',*/
Sort by keys using key function
; const objectWithUnsortedKeys = key4: 'e' key1: 'c' key3: 'c' key2: 'd' key5: 'a'; var sortedObject = ; console;/* key5: 'a', key4: 'e', key3: 'c', key2: 'd', key1: 'c'*/