Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created April 8, 2022 19:16
Show Gist options
  • Save hawkeye64/c19dbdafb9629d3116b06f2c6a773312 to your computer and use it in GitHub Desktop.
Save hawkeye64/c19dbdafb9629d3116b06f2c6a773312 to your computer and use it in GitHub Desktop.
JavaScript to convert camelCase to snake_case (server-side)
'use strict'
// converts camelCase to snake_case
// used to convert to database
// myVar => my_var
function toSnakeCase (objectArrayOrString) {
return keysToSnake(objectArrayOrString)
}
const toSnake = (s) => {
// return this.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();});
return s.split(/(?=[A-Z])/).join('_').toLowerCase()
}
const isArray = function (a) {
return Array.isArray(a)
}
const isObject = function (o) {
return o === Object(o) && !isArray(o) && typeof o !== 'function'
}
const keysToSnake = function (o) {
if (isObject(o)) {
const n = {}
Object.keys(o)
.forEach((k) => {
n[toSnake(k)] = keysToSnake(o[k])
})
return n
}
else if (isArray(o)) {
return o.map((i) => {
return keysToSnake(i)
})
}
return o
}
module.exports = toSnakeCase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment