Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active October 31, 2022 10:58
Show Gist options
  • Save crshmk/b17653ebfe6326264e888297028ef483 to your computer and use it in GitHub Desktop.
Save crshmk/b17653ebfe6326264e888297028ef483 to your computer and use it in GitHub Desktop.
Apply a transform function to object keys, recursively
import { fromPairs, is, map, pipe, toPairs } from 'ramda'
const isObject = is(Object)
const transformKey = transform =>
([k, v]) => !isObject(v) ? [transform(k), v] :
[transform(k), mapKeys(transform)(v)]
const mapKeys = transform =>
pipe(
toPairs,
map(transformKey(transform)),
fromPairs
)
export default mapKeys
@crshmk
Copy link
Author

crshmk commented Oct 31, 2022

import mapKeys from './mapKeys'
import { toUpper } from 'ramda'

const toUpperKeys = mapKeys(toUpper)

const obj = {
  one: 1,
  two: 2,
  three: {
    four: 4,
    five: {
      six: {
        seven: 7,
        eight: {
          nine: 9
        }
      }
    }
  }
}

toUpperKeys(obj)
/*
{
  ONE: 1,
  TWO: 2,
  THREE: {
    FOUR: 4,
    FIVE: { SIX: { SEVEN: 7, EIGHT: { NINE: 9 } } }
  }
}
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment