JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)
How do you convert strings between camelCase, snake_case, and kebab-case in JavaScript?
mid LevelCode ExampleFormsPerformanceHTTP & REST APIs
Fullstack and frontend engineers frequently receive snake_case payloads from backends (Python, Go, PostgreSQL) and need to transform them to camelCase for client models, or transform them to kebab-case for CSS class names and URL slugs.
1. Universal toCamelCase (handles snake_case and kebab-case)
javascript
function toCamelCase(str) {
return str
.trim()
.replace(/[-_\s]+(.)?/g, (_, char) => (char ? char.toUpperCase() : ''));
}
console.log(toCamelCase("user_first_name")); // "userFirstName"
console.log(toCamelCase("user-billing-id")); // "userBillingId"
console.log(toCamelCase("created_at_timestamp")); // "createdAtTimestamp"
2. toSnakeCase and toKebabCase
javascript
function toSnakeCase(str) {
return str
.trim()
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
.replace(/[-\s]+/g, '_')
.toLowerCase();
}
function toKebabCase(str) {
return str
.trim()
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/[_\s]+/g, '-')
.toLowerCase();
}
console.log(toSnakeCase("userFirstName")); // "user_first_name"
console.log(toKebabCase("userFirstName")); // "user-first-name"
3. Deep Object Keys Converter (Real-World Interview Question)
Interviewers often ask: "Write a recursive function that converts all keys of a nested API response object from snake_case to camelCase":
javascript
function camelizeKeys(obj) {
if (Array.isArray(obj)) {
return obj.map(item => camelizeKeys(item));
}
if (obj !== null && typeof obj === 'object' && !(obj instanceof Date) && !(obj instanceof RegExp)) {
return Object.keys(obj).reduce((acc, key) => {
const camelKey = key.replace(/_([a-z0-9])/gi, (_, char) => char.toUpperCase());
acc[camelKey] = camelizeKeys(obj[key]);
return acc;
}, {});
}
return obj;
}
const apiResponse = {
user_id: 101,
billing_details: {
card_type: "visa",
card_last_four: "4242"
},
order_history: [
{ order_id: 1, total_amount: 99.99 }
]
};
console.log(camelizeKeys(apiResponse));
/* Output:
{
userId: 101,
billingDetails: {
cardType: "visa",
cardLastFour: "4242"
},
orderHistory: [
{ orderId: 1, totalAmount: 99.99 }
]
}
*/