JAVASCRIPT

Convert API Response Keys from Snake Case to Camel Case

A JavaScript utility function to recursively transform object keys from snake_case to camelCase, common for API response consistency.

function snakeToCamel(s) {
    return s.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
}

function convertKeysToCamelCase(data) {
    if (typeof data !== 'object' || data === null) {
        return data;
    }

    if (Array.isArray(data)) {
        return data.map(item => convertKeysToCamelCase(item));
    }

    const newObject = {};
    for (const key in data) {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
            const newKey = snakeToCamel(key);
            newObject[newKey] = convertKeysToCamelCase(data[key]);
        }
    }
    return newObject;
}

// Usage example:
// const apiResponse = {
//     user_id: 123,
//     user_name: 'John Doe',
//     user_profile: {
//         first_name: 'John',
//         last_name: 'Doe',
//         email_address: '[email protected]',
//         addresses: [
//             { street_name: 'Main St', street_number: 123 },
//             { street_name: 'Park Ave', street_number: 456 }
//         ]
//     },
//     last_login_at: '2023-10-27T10:00:00Z'
// };

// const camelCaseData = convertKeysToCamelCase(apiResponse);
// console.log(JSON.stringify(camelCaseData, null, 2));
/* Expected output:
{
  "userId": 123,
  "userName": "John Doe",
  "userProfile": {
    "firstName": "John",
    "lastName": "Doe",
    "emailAddress": "[email protected]",
    "addresses": [
      {
        "streetName": "Main St",
        "streetNumber": 123
      },
      {
        "streetName": "Park Ave",
        "streetNumber": 456
      }
    ]
  },
  "lastLoginAt": "2023-10-27T10:00:00Z"
}
*/
How it works: This snippet provides a JavaScript utility to transform object keys from `snake_case` to `camelCase`. This is particularly useful when integrating with APIs that return `snake_case` keys, ensuring consistency with common JavaScript naming conventions. The `convertKeysToCamelCase` function recursively traverses nested objects and arrays, applying the `snakeToCamel` transformation to each key, making the API response data easier to work with in frontend applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs