Skip to content

convert property names from/to camelCase and snake_case

License

Notifications You must be signed in to change notification settings

craftgear/snake-camel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

51 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

snake-camel

Actions Status

convert property names from/to camelCase and snake_case recursively.

How to use

import

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

toCamel - convert snake_case 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 snake_case

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],
  },
]

About

convert property names from/to camelCase and snake_case

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published