https://github.com/keithamus/sort-object-keys
Sort an object's keys, including an optional key list
https://github.com/keithamus/sort-object-keys
Last synced: 12 months ago
JSON representation
Sort an object's keys, including an optional key list
- Host: GitHub
- URL: https://github.com/keithamus/sort-object-keys
- Owner: keithamus
- Created: 2015-11-30T20:08:07.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2025-03-02T18:47:35.000Z (about 1 year ago)
- Last Synced: 2025-03-31T09:03:09.629Z (about 1 year ago)
- Language: JavaScript
- Size: 43.9 KB
- Stars: 31
- Watchers: 2
- Forks: 6
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
- awesome-e18e - sort-object-keys - Sort object keys with optional key list specification. (Utilities / Data Structures)
README
# Sort Object
[](https://travis-ci.org/keithamus/sort-object-keys)
Returns a copy of an object with all keys sorted.
The second argument is optional and is used for ordering - to provide custom sorts. You can either pass an array containing ordered keys or a function to sort the keys (same signature as in [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)).
```js
const assert = require('assert');
const sortObject = require('sort-object-keys');
assert.equal(JSON.stringify({
c: 1,
b: 1,
d: 1,
a: 1,
}), JSON.stringify({
a: 1,
b: 1,
c: 1,
d: 1,
}));
assert.equal(JSON.stringify(sortObject({
c: 1,
b: 1,
d: 1,
a: 1,
}, ['b', 'a', 'd', 'c'])), JSON.stringify({
b: 1,
a: 1,
d: 1,
c: 1,
}));
function removeKeyAncCompareIndex(keyA, keyB){
var a = parseInt(keyA.slice(4));
var b = parseInt(keyB.slice(4));
return a - b;
}
assert.equal(JSON.stringify(sortObject({
"key-1": 1,
"key-3": 1,
"key-10": 1,
"key-2": 1,
}, removeKeyAncCompareIndex)), JSON.stringify({
"key-1": 1,
"key-2": 1,
"key-3": 1,
"key-10": 1,
}));
```