JAVASCRIPT
Transform API Response Keys from Snake_case to CamelCase
Efficiently restructure API response data on the client-side, converting common formats like snake_case keys to camelCase to match typical JavaScript naming conventions.
function snakeToCamel(s) {
return s.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
}
function transformKeysToCamelCase(data) {
if (Array.isArray(data)) {
return data.map(item => transformKeysToCamelCase(item));
} else if (typeof data === 'object' && data !== null) {
return Object.keys(data).reduce((acc, key) => {
const camelKey = snakeToCamel(key);
acc[camelKey] = transformKeysToCamelCase(data[key]);
return acc;
}, {});
} else {
return data;
}
}
// Usage example:
const apiResponse = {
"user_profile": {
"first_name": "John",
"last_name": "Doe",
"contact_info": {
"email_address": "[email protected]",
"phone_number": "123-456-7890"
},
"preferences_list": [
{ "preference_id": 1, "preference_name": "email_notifications" },
{ "preference_id": 2, "preference_name": "sms_alerts" }
]
},
"last_updated_at": "2023-10-27T10:00:00Z"
};
const camelCaseData = transformKeysToCamelCase(apiResponse);
console.log(JSON.stringify(camelCaseData, null, 2));
/* Expected output:
{
"userProfile": {
"firstName": "John",
"lastName": "Doe",
"contactInfo": {
"emailAddress": "[email protected]",
"phoneNumber": "123-456-7890"
},
"preferencesList": [
{ "preferenceId": 1, "preferenceName": "emailNotifications" },
{ "preferenceId": 2, "preferenceName": "smsAlerts" }
]
},
"lastUpdatedAt": "2023-10-27T10:00:00Z"
}
*/
How it works: This JavaScript utility helps align API response data with standard frontend naming conventions, specifically converting object keys from `snake_case` to `camelCase`. The `snakeToCamel` helper function performs the string transformation. The `transformKeysToCamelCase` function recursively traverses the data structure (handling objects and arrays) to apply this transformation to all nested keys. This ensures consistency in your codebase, making it easier to work with API data in JavaScript applications.