Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created April 8, 2022 19:14
Show Gist options
  • Save hawkeye64/983363f480ef91f38eed2284757977a3 to your computer and use it in GitHub Desktop.
Save hawkeye64/983363f480ef91f38eed2284757977a3 to your computer and use it in GitHub Desktop.
JavaScript to convert snake_case to camelCase (server-side)
'use strict'
// converts snake_case to camelCase
// used to convert from database
// my_var => myVar
function toCamelCase (objectArrayOrString) {
return keysToCamel(objectArrayOrString)
}
const toCamel = (s) => {
// return name.replace(/_([a-z])/g, g => g[1].toUpperCase())
return s.replace(/([-_][a-z])/ig, ($1) => {
return $1.toUpperCase()
.replace('-', '')
.replace('_', '')
})
}
const isArray = function (a) {
return Array.isArray(a)
}
const isObject = function (o) {
return o === Object(o) && !isArray(o) && typeof o !== 'function'
}
const keysToCamel = function (o) {
if (isObject(o)) {
const n = {}
Object.keys(o)
.forEach((k) => {
n[toCamel(k)] = keysToCamel(o[k])
})
return n
}
else if (isArray(o)) {
return o.map((i) => {
return keysToCamel(i)
})
}
return o
}
module.exports = toCamelCase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment