Skip to the solution
MediumFrontendAsked in 20247 min read

Convert Between snake_case and camelCase Object Keys (Including Nested Objects)

3.6k views

The problem

Problem, as an interviewer would state it: "Write snakeToCamel(obj) and camelToSnake(obj) — recursively convert every object key between snake_case and camelCase, correctly handling nested objects and arrays of objects."

Examples:

Code
snakeToCamel({ user_id: 1, address_info: { zip_code: "10001" } });
// { userId: 1, addressInfo: { zipCode: "10001" } }

Clarifying questions expected:

  • Should this recurse into arrays too, converting keys of objects INSIDE an array value?
  • What about keys that are already in the target case, or contain numbers?
  • Should Date objects or other non-plain-object values be recursed into, or left alone?

Code / implementation expected: Yes — real, direct proof on a genuinely nested structure (object + array of objects), including a full round-trip back to the original.

  • object
  • regex

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: snakeToCamel/camelToSnake correctly convert a deeply nested object (including a nested array of objects) and round-trip exactly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 53 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Deep Map Keys

Continue