Created
April 8, 2022 19:16
-
-
Save hawkeye64/c19dbdafb9629d3116b06f2c6a773312 to your computer and use it in GitHub Desktop.
JavaScript to convert camelCase to snake_case (server-side)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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