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
3 Answers
Reset to default 10You 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"));