59 lines
1.3 KiB
TypeScript
59 lines
1.3 KiB
TypeScript
// camelCase to snake_case
|
|
export function camelToSnakeCase(o: any): any {
|
|
if (o === null || typeof o != "object") {
|
|
return o;
|
|
}
|
|
|
|
if (Array.isArray(o)) {
|
|
return o.map(camelToSnakeCase);
|
|
}
|
|
|
|
const build: { [key: string]: string } = {};
|
|
for (const key in o) {
|
|
const newKey = toSnake(key);
|
|
|
|
let value = o[key];
|
|
|
|
if (typeof value === "object") {
|
|
value = camelToSnakeCase(value);
|
|
}
|
|
|
|
build[newKey] = value;
|
|
}
|
|
return build;
|
|
}
|
|
|
|
// snake_case to camelCase
|
|
export function snakeToCamelCase(o: any): any {
|
|
if (o === null || typeof o != "object") {
|
|
return o;
|
|
}
|
|
|
|
if (Array.isArray(o)) {
|
|
return o.map(snakeToCamelCase);
|
|
}
|
|
|
|
const build: { [key: string]: string } = {};
|
|
for (const key in o) {
|
|
const newKey = toCamel(key);
|
|
|
|
let value = o[key];
|
|
|
|
if (typeof value === "object") {
|
|
value = snakeToCamelCase(value);
|
|
}
|
|
|
|
build[newKey] = value;
|
|
}
|
|
return build;
|
|
}
|
|
|
|
function toCamel(s: string): string {
|
|
return s.replace(/([-_][a-z])/gi, ($1) => {
|
|
return $1.toUpperCase().replace("-", "").replace("_", "");
|
|
});
|
|
}
|
|
|
|
function toSnake(s: string): string {
|
|
return s.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
} |