I am looking to develop a Typescript function that can deeply traverse a plain object and convert all snake_case keys to camelCase. Additionally, I need a function that can convert camelCase keys to snake_case throughout the object.
While implementing this in JavaScript is straightforward, I find it challenging in Typescript due to the need to consider types.
Can anyone advise me on how to approach this task in Typescript?
This is my JavaScript version for reference:
const keyToSnakeCase = obj => {
if (Array.isArray(obj)) {
return obj.map(el => keyToSnakeCase(el));
}
if (!isPlainObject(obj)) {
return obj;
}
const newObj = {};
Object.entries(obj).forEach(([key, value]) => {
newObj[camelCase(key)] = keyToSnakeCase(value);
});
return newObj;
};
const keyToCamelCase = obj => {
if (Array.isArray(obj)) {
return obj.map(el => keyToCamelCase(el));
}
if (!isPlainObject(obj)) {
return obj;
}
const newObj = {};
Object.entries(obj).forEach(([key, value]) => {
newObj[snakeCase(key)] = keyToCamelCase(value);
});
return newObj;
};