Last active
February 24, 2023 14:38
-
-
Save imbudhiraja/dcafa0ad45a1e5edc19e142ea6822c50 to your computer and use it in GitHub Desktop.
Converting Object Keys from Snake Case, Kebab Case to Camel Case with JavaScript
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
const mongoose = require('mongoose'); | |
const toCamel = (string) => string.replace(/([-_][a-z])/gi, ($1) => $1 | |
.toUpperCase() | |
.replace('-', '') | |
.replace('_', '')); | |
const isObject = (args) => args === Object(args) && !Array.isArray(args) && typeof args !== 'function'; | |
const keysToCamel = (args) => { | |
if (isObject(args)) { | |
const n = {}; | |
Object.keys(args).forEach((k) => { | |
if (mongoose.Types.ObjectId.isValid(args[k])) { | |
n[toCamel(k)] = args[k]; | |
} else { | |
n[toCamel(k)] = keysToCamel(args[k]); | |
} | |
}); | |
return n; | |
} | |
if (Array.isArray(args)) { | |
return args.map((i) => keysToCamel(i)); | |
} | |
return args; | |
}; | |
exports.keysToCamel = keysToCamel; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment