Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert snake case to camelcase in typescripts?

I want to convert a string of that is in snake case to camel case using TypeScript. Example: item_name to itemName, Unit_Price to unitPrice

like image 296
Badrul Avatar asked Jan 28 '26 15:01

Badrul


2 Answers

You can use this function which I think is more readable and also tinier:

const snakeCaseToCamelCase = input =>
  input
    .split("_")
    .reduce(
      (res, word, i) =>
        i === 0
          ? word.toLowerCase()
          : `${res}${word.charAt(0).toUpperCase()}${word
              .substr(1)
              .toLowerCase()}`,
      ""
    );
like image 148
Vahid Avatar answered Jan 30 '26 05:01

Vahid


for snakecase to camelcase use this keysToCamel({ your object })

  keysToCamel(o: unknown): unknown {
    if (o === Object(o) && !Array.isArray(o) && typeof o !== 'function') {
      const n = {};
      Object.keys(o).forEach((k) => {
        n[this.toCamel(k)] = this.keysToCamel(o[k]);
      });
      return n;
    } else if (Array.isArray(o)) {
      return o.map((i) => {
        return this.keysToCamel(i);
      });
    }
    return o;
  }

  toCamel(s: string): string {
    return s.replace(/([-_][a-z])/gi, ($1) => {
      return $1.toUpperCase().replace('-', '').replace('_', '');
    });
  }

and for camelcase to snake user this keysToSnake({your object})

  keysToSnake(o: unknown): unknown {
    if (o === Object(o) && !Array.isArray(o) && typeof o !== 'function') {
      const n = {};
      Object.keys(o).forEach((k) => {
        n[this.toSnake(k)] = this.keysToSnake(o[k]);
      });
      return n;
    } else if (Array.isArray(o)) {
      return o.map((i) => {
        return this.keysToSnake(i);
      });
    }
    return o;
  }

  toSnake(s: string): string {
    return s.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
  }
like image 36
H.Azizkhani Avatar answered Jan 30 '26 03:01

H.Azizkhani