What is sort-keys?
The sort-keys npm package is used to sort the keys of an object, either in ascending or descending order, based on a custom comparator function if provided. This can be particularly useful for organizing JSON objects for readability or for ensuring that objects are in a consistent order when stringifying them, which can be important for hashing and caching mechanisms.
What are sort-keys's main functionalities?
Sort keys in ascending order
Sorts the keys of an object in ascending order. This is the default behavior without providing any additional options.
const sortKeys = require('sort-keys');
const sorted = sortKeys({c: 0, a: 0, b: 0});
console.log(sorted); // Output: { a: 0, b: 0, c: 0 }
Sort keys using a custom comparator
Sorts the keys of an object using a custom comparator function. In this example, the keys are sorted in descending order.
const sortKeys = require('sort-keys');
const sorted = sortKeys({a: 0, b: 1, c: 2}, {
compare: (a, b) => b.localeCompare(a)
});
console.log(sorted); // Output: { c: 2, b: 1, a: 0 }
Deep sorting of nested objects
Sorts the keys of an object and all nested objects. This is useful for deep sorting complex objects.
const sortKeys = require('sort-keys');
const obj = {
c: {c2: 0, c1: 0},
a: {a2: 0, a1: 0},
b: 0
};
const sorted = sortKeys(obj, {deep: true});
console.log(sorted); // Output: { a: { a1: 0, a2: 0 }, b: 0, c: { c1: 0, c2: 0 } }
Other packages similar to sort-keys
lodash.sortby
Provides a function to sort arrays of objects based on the values at specified keys. While sort-keys sorts the keys of an object, lodash.sortby sorts the elements of an array based on one or more properties.
deep-sort-object
Similar to sort-keys with deep sorting capabilities, but deep-sort-object is specifically designed to handle deep sorting of objects without the need for additional configuration.
sort-keys
Sort the keys of an object
Useful to get a deterministically ordered object, as the order of keys can vary between engines.
Install
$ npm install --save sort-keys
Usage
const sortKeys = require('sort-keys');
sortKeys({c: 0, a: 0, b: 0});
sortKeys({b: {b: 0, a: 0}, a: 0}, {deep: true});
sortKeys({c: 0, a: 0, b: 0}, {
compare: (a, b) => -a.localeCompare(b)
});
API
sortKeys(input, [options])
Returns a new object with sorted keys.
input
Type: Object
options
deep
Type: boolean
Recursively sort keys.
compare
Type: Function
Compare function.
License
MIT © Sindre Sorhus