Skip to content

Instantly share code, notes, and snippets.

@imbudhiraja
Last active February 24, 2023 14:38
Show Gist options
  • Save imbudhiraja/dcafa0ad45a1e5edc19e142ea6822c50 to your computer and use it in GitHub Desktop.
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
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