最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert snake case to camelcase in typescripts? - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited Jan 18, 2019 at 0:43 Vahid 7,6015 gold badges46 silver badges67 bronze badges asked Jan 17, 2019 at 18:35 BadrulBadrul 1,1493 gold badges9 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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

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

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"));
发布评论

评论列表(0)

  1. 暂无评论