CodePark/ problems / Camel-case all keys
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Recursion over nested objects

Camel-case all keys

easyabout 12 minutes in an interview

An API returns snake_case keys such as first_name. Your frontend wants camelCase keys such as firstName. Implement camelCaseKeys(value), which returns a new value with every object key converted, at every depth.

Converting a key: each underscore followed by a character is removed, and that character is upper-cased. So created_at_utc becomes createdAtUtc and address_line_2 becomes addressLine2. Keys contain only lowercase letters, digits and single underscores, and never start or end with an underscore.

Which values to walk into:

  • Plain objects: convert their keys and walk into their values.
  • Arrays: keep them as arrays and walk into each element. Objects inside arrays get converted too.
  • Everything else (strings, numbers, null, Date objects) is returned as it is. String values are never changed.

Don't modify the input.

Input: camelCaseKeys({ first_name: 'Ada', home_address: { zip_code: '02139' } }) Output: { firstName: 'Ada', homeAddress: { zipCode: '02139' } }
Input: camelCaseKeys([{ item_id: 1 }, 'a_b']) Output: [{ itemId: 1 }, 'a_b']the string value keeps its underscore