snake-camel

convert object keys from/to camelCase and snake_case

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
snake-camel
961.0.82 years ago4 years agoMinified + gzip package size for snake-camel in KB

Readme

snake-camel
Actions Status
convert property names from/to camelCase and snakecase recursively.

How to use

import

import { toCamel, toSnake } from 'snake-camel';

toCamel - convert snakecase to camelCase

toCamel({
  foo_bar: 'foo',
  bar_baz: [1, 2, 3],
  qux_foo: {
    baz_qux: 'baz',
  },
  baz_qux: [{ baz_foo: 1 }, { qux_bar: { foo_foo: 2 } }, true, 1, 'fooBar', 'barBaz'],
})
yields:
{
   fooBar: 'foo',
   barBaz: [1, 2, 3],
   quxFoo: {
     bazQux: 'baz',
   },
   bazQux: [{ bazFoo: 1 }, { quxBar: { fooFoo: 2 } }, true, 1, 'fooBar', 'barBaz'],
}

toSnake - convert camelCase to snakecase

toSnake({
  fooBar: 'foo',
  barBaz: [1, 2, 3],
  quxFoo: {
    bazQux: 'baz',
  },
  bazQux: [{ bazFoo: 1 }, { quxBar: { fooFoo: 2 } }, true, 1, 'fooBar', 'barBaz'],
})
yields:
{
  foo_bar: 'foo',
  bar_baz: [1, 2, 3],
  qux_foo: {
    baz_qux: 'baz',
  },
  baz_qux: [{ baz_foo: 1 }, { qux_bar: { foo_foo: 2 } }, true, 1, 'fooBar', 'barBaz'],
}

dealing with an Array of Objects

Mapping toCamle / toSnake over an array does the trick.
const snakeCase = {
    foo_bar: 'foo',
    bar_baz: [1, 2, 3],
};
const arr = [snakeCase, snakeCase].map(toCamel);
yields:
[
  {
    fooBar: 'foo',
    barBaz: [1, 2, 3],
  },
  {
    fooBar: 'foo',
    barBaz: [1, 2, 3],
  },
]