Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save oojikoo/2dfedcb54c8802b4ced80f5f2a7f0b5d to your computer and use it in GitHub Desktop.
Save oojikoo/2dfedcb54c8802b4ced80f5f2a7f0b5d to your computer and use it in GitHub Desktop.

Revisions

  1. @imbudhiraja imbudhiraja revised this gist Mar 29, 2019. 1 changed file with 4 additions and 6 deletions.
    10 changes: 4 additions & 6 deletions convert-keys-to-camel-case
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    const mongoose = require('mongoose');

    const toCamel = (string) => string.replace(/([-_][a-z])/gi, ($1) => $1
    .toUpperCase()
    .replace('-', '')
    @@ -10,12 +12,8 @@ const keysToCamel = (args) => {
    const n = {};

    Object.keys(args).forEach((k) => {
    if (k.toLowerCase().includes('id')) {
    if (k.toLowerCase() === '_id') {
    n[k] = args[k];
    } else {
    n[toCamel(k)] = args[k];
    }
    if (mongoose.Types.ObjectId.isValid(args[k])) {
    n[toCamel(k)] = args[k];
    } else {
    n[toCamel(k)] = keysToCamel(args[k]);
    }
  2. @imbudhiraja imbudhiraja created this gist Mar 28, 2019.
    33 changes: 33 additions & 0 deletions convert-keys-to-camel-case
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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 (k.toLowerCase().includes('id')) {
    if (k.toLowerCase() === '_id') {
    n[k] = args[k];
    } else {
    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;