-
-
Save oojikoo/2dfedcb54c8802b4ced80f5f2a7f0b5d 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 hidden or 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