Skip to content

Instantly share code, notes, and snippets.

@kentbrew kentbrew/sortByKeys.md
Last active Aug 30, 2019

Embed
What would you like to do?
Sorting a JSON Object by Key Name

Sorting a JSON Object by Key Name

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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.