While performing eyeball-based QA for an API update I needed a fast way to reformat output so that all keys would be in the same order. Here's what I came up with:
sortByKeys = input => {
// default: return anything whose typeof is NOT "object"
let result = input;
// do we have an object? look inside
if (input && typeof input === "object") {
// do we have an array?
if (Array.isArray(input)) {
// map an array by recursing through each element
result = input.map(sortByKeys);
} else {
// sort an object by recursing through each child
result = Object.keys(input).sort().
reduce(
(obj, key) => ({
...obj, [key]: sortByKeys(input[key])
}),
{});
}
}
return result;
};