Created
June 3, 2019 13:29
-
-
Save aleph-naught2tog/938dd20dfc53e91da952569fd5655e2d to your computer and use it in GitHub Desktop.
Sort an object by keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sortByKeysLegibly = maybeObject => { | |
// presumably we want the array to stay ordered. Possibly not, but if there is | |
// anything that should preserve order, it's an array | |
if (maybeObject instanceof Array) { | |
return maybeObject; | |
} | |
// don't sort strings etc | |
if (typeof maybeObject !== 'object') { | |
return maybeObject; | |
} | |
const sortedKeys = Object.keys(maybeObject).sort(); | |
return sortedKeys.reduce((objectSoFar, currentKey) => { | |
const currentValue = maybeObject[currentKey]; | |
const maybeSortedValue = sortByKeysLegibly(currentValue); | |
return { | |
...objectSoFar, | |
[currentKey]: maybeSortedValue | |
}; | |
}, {}); | |
}; | |
// and for JSON | |
const sortJson = jsonValue => JSON.stringify(sortByKeysLegibly(JSON.parse(jsonValue))); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ugly code golf version | |
const sortKeys = v => | |
v instanceof Array || typeof v !== 'object' | |
? v | |
: Object.keys(v) | |
.sort() | |
.reduce( | |
(acc, k) => ({ | |
...acc, | |
[k]: sortKeys(v[k]) | |
}), | |
{} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment