Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

convert-object-keys

trezy-studios42BSD-3-Clause1.0.1

Recursively convert an object's keys into anything you want.

api, camelcase, camelize, capitalize, case, changecase, convert, first, humanize, letter, lettercase, lowercase, object, pretty, snakecase, string, text, titleize, transform, transformcase, underscore, uppercamelcase, uppercamelize, uppercase

readme

convert-object-keys

Recursively convert an object's keys into anything you want.


Build status Code Coverage Dependencies Maintainability BSD-3-Clause License Version

Code of Conduct All Contributors PRs Welcome

Watch on GitHub Star on GitHub Tweet

Use Case

convert-object-keys is a tiny, versatile library that can recursively convert your object keys with any transformer method you want. My original use case was this: I was building a JavaScript project that needed to interact with both the [Firebase][firebase] and the [Twilio][twilio] APIs. The issue is that my lettercase was different everywhere. Since I was using JavaScript, my variables were all camel cased (thisIsACamelCasedVariable). Firebase, however, sent all their JSON keys in snake case (this_is_a_snake_cased_variable), while Twilio sent all of their JSON keys in upper camel case (ThisIsAnUpperCamelCasedVariable).

To make matters worse, my ESlint config enforced camel casing and I didn't want to change it! Instead, I wrote a couple of tools to solve the issue: convert-object-keys and transform-string-case.

Usage

To use convert-object-keys, you need to pass it an object and a transformer method.

import convertObjectKeys from 'convert-object-keys'

const objectToConvert = {
  "FOO": "lorem ipsum",
  "BAR": "lorem ipsum",
  "BAZ": "lorem ipsum",
}

const transformer = (key) => {
  return key.toLowerCase()
}

convertObjectKeys(objectToConvert, transformer)
/* Result:
{
  "foo": "lorem ipsum",
  "bar": "lorem ipsum",
  "baz": "lorem ipsum",
}
*/

By default, the convertObjectKeys method will convert all keys in the object recursively, including traversing into arrays. You can control this behavior by passing a boolean in as the third parameter.

import convertObjectKeys from 'convert-object-keys'

const objectToConvert = {
  "FOO": {
    "BAR": "lorem ipsum",
  },
}

const transformer = (key) => {
  return key.toLowerCase()
}

convertObjectKeys(objectToConvert, transformer, true /* Recursive conversion enabled */)
/* Result:
{
  "foo": {
    "bar": "lorem ipsum",
  },
}
*/

convertObjectKeys(objectToConvert, transformer, true /* Recursive conversion disabled */)
/* Result:
{
  "foo": {
    "BAR": "lorem ipsum",
  },
}
*/

Contributing

If you want to contribute, make sure to check out our contributing guide!

Contributors

Trezy
Trezy

💻 📖 🤔 🚇 🚧 🔧 ⚠️