Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Last active August 30, 2019 15:37
Show Gist options
  • Save kentbrew/50270d50607c773ade328f2f83bf5fa8 to your computer and use it in GitHub Desktop.
Save kentbrew/50270d50607c773ade328f2f83bf5fa8 to your computer and use it in GitHub Desktop.
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