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
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()}`);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With