Utility that return copy of object with sorted keys
npm install sort-object-properties --save
//ES6
import sort from 'sort-object-properties';
//CommonJS
var sort = require('sort-object-properties');
const objectWithUnsortedKeys = {
d: 'value1',
c: 'value2',
e: 'value3',
b: 'value4',
a: 'value5'
};
var sortedObject = sort(objectToSort);
console.log(sortedObject);
/*
a: 'value5',
b: 'value4',
c: 'value2',
d: 'value1',
e: 'value3'
*/
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 |
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 |
Sorts object properties by its keys.
Argument | Type | Optional | Description |
---|---|---|---|
obj | PropertyObject |
false | Object to sort |
direction | SortDirection , Number |
true | Sort direction |
Constant with sort directions, use that const or just use plain numbers in function calls.
Name | Value |
---|---|
ascending | 1 |
descending | -1 |
const objectWithUnsortedValues = {
key1: 'd',
key2: 'a',
key3: 'e',
key4: 'b',
key5: 'c'
};
//ES6 syntax
var sortedObject = sort(objectWithUnsortedValues, ({value: valueA}, {value: valueB}) => valueA > valueB);
//ES5 syntax
var sortedObject = sort(objectWithUnsortedValues, function (a, b){ return a.value > b.value;});
console.log(sortedObject);
/*
key2: 'a',
key4: 'b',
key5: 'c'
key1: 'd',
key3: 'e',
*/
import { value as sortByValue } from 'sort-object-properties';
const objectWithUnsortedValues = {
key1: 'd',
key2: 'a',
key3: 'e',
key4: 'b',
key5: 'c'
};
var sortedObject = sortByValue(objectWithUnsortedValues);
console.log(sortedObject);
/*
key2: 'a',
key4: 'b',
key5: 'c'
key1: 'd',
key3: 'e',
*/
import { key as sortByKey, sortDirection } from 'sort-object-properties';
const objectWithUnsortedKeys = {
key4: 'e',
key1: 'c',
key3: 'c',
key2: 'd',
key5: 'a'
};
var sortedObject = sortByKey(objectWithUnsortedKeys, sortDirection.descending);
console.log(sortedObject);
/*
key5: 'a',
key4: 'e',
key3: 'c',
key2: 'd',
key1: 'c'
*/