Skip to content

Instantly share code, notes, and snippets.

@NetOpWibby
Forked from aleph-naught2tog/prettySortByKeys.js
Created February 18, 2020 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NetOpWibby/11cb5be8c8d9770228002f26123eb817 to your computer and use it in GitHub Desktop.
Save NetOpWibby/11cb5be8c8d9770228002f26123eb817 to your computer and use it in GitHub Desktop.
Sort an object by keys
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)));
// 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