简体   繁体   English

如何在打字稿中将蛇形字母转换为驼色字母?

[英]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.我想使用 TypeScript 将蛇形的字符串转换为驼色。 Example: item_name to itemName , Unit_Price to unitPrice示例: item_nameitemNameUnit_PriceunitPrice

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()}`,
      ""
    );

I have solved this problems by below code.我已经通过下面的代码解决了这个问题。 But i am looking another better solutions.但我正在寻找另一个更好的解决方案。

let userOutPut = '';
function snakeCaseToCamelCase(userInput: string) {
  const userInputSplit = userInput.split('_');
  let x = 0;
  for (const prm of userInputSplit) {
    if (x === 0) {
      userOutPut = prm.toLowerCase();
    } else {
      userOutPut += prm.substr(0, 1).toUpperCase() + prm.substr(1).toLowerCase();
    }
    x++;
  } 
  return userOutPut;
}

// Calling method
console.log(snakeCaseToCamelCase("item_name"));

for snakecase to camelcase use this keysToCamel({ your object })对于snakecase到camelcase使用这个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({your object})用户这个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()}`);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM