convert-object-keys

1.0.1 • Public • Published

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

💻 📖 🤔 🚇 🚧 🔧 ⚠️

Dependents (0)

Package Sidebar

Install

npm i convert-object-keys

Weekly Downloads

6

Version

1.0.1

License

BSD-3-Clause

Unpacked Size

25 kB

Total Files

11

Last publish

Collaborators

  • trezy