Skip to content

Object

Sort Keys

This snippet can be used to sort object keys.

js
const sortObjKey = (obj) => {
  return Object.keys(obj)
    .sort()
    .reduce((acc, key) => {
      acc[key] = obj[key]
      return acc
    }, {})
}

Example

js
const unsorted = {
  b: 'foo',
  c: 'bar',
  a: 'baz'
}

sortObjKey(unsorted) // {a: 'baz', b: 'foo', c: 'bar'}

massCode released under the AGPL v3 License.
Snippet collection released under the CC-BY-4.0 License.