Convert the key strings with a regex (_x → X for camel, X → _x for snake), then rebuild the object with the new keys. Interviewers then ask for it deep: recurse into nested plain objects and into arrays, but leave values like Date, Map and class instances alone, and never change the input. The strong answer also splits keys into words properly (XMLHttpRequest → xml_http_request, userID → user_id), keeps leading underscores (_id), handles cycles, and refuses keys that collide after conversion. This is exactly the layer between a snake_case API and camelCase JavaScript.
Convert all keys within an object into snake_case/camelCase
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
snakeToCamel replaces each _ followed by a letter or digit with the upper-cased character; camelToSnake puts _ before each capital and lower-cases it. Rebuilding with Object.entries changes the keys and copies the values as they are. This only touches the top level.
const snakeToCamel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());const camelToSnake = (s) => s.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());// Shallow: the object's own keys only.function mapKeys(obj, convert) {const out = {};for (const [key, value] of Object.entries(obj)) out[convert(key)] = value;return out;}const keysToCamel = (obj) => mapKeys(obj, snakeToCamel);const keysToSnake = (obj) => mapKeys(obj, camelToSnake);
passes 4 checks run on every build, against the native method where there is one
- snake_case keys become camelCase
- camelCase keys become snake_case
- values are not touched
- round trip on simple keys
API payloads nest: an order has line items, a user has an address. Recurse into arrays and plain objects (prototype Object.prototype or null) and return anything else unchanged, so a Date stays a Date and a class instance keeps its own fields. Build new objects instead of renaming in place, so the caller's data is untouched.
const snakeToCamel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());const camelToSnake = (s) => s.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());// Only plain objects get their keys changed: a Date, a Map or a class instance is data, not a record.const isPlainObject = (v) => {if (v === null || typeof v !== 'object') return false;const proto = Object.getPrototypeOf(v);return proto === Object.prototype || proto === null;};function convertKeysDeep(value, convert) {if (Array.isArray(value)) return value.map((item) => convertKeysDeep(item, convert));if (!isPlainObject(value)) return value;const out = {};for (const [key, inner] of Object.entries(value)) out[convert(key)] = convertKeysDeep(inner, convert);return out;}const keysToCamel = (value) => convertKeysDeep(value, snakeToCamel);const keysToSnake = (value) => convertKeysDeep(value, camelToSnake);
passes 4 checks run on every build, against the native method where there is one
- nested objects and arrays of objects are converted
- Dates, Maps and class instances are left alone
- primitives, null and arrays of primitives pass through
- the input is not changed
Naive regexes turn userID into user_i_d and XMLHttpRequest into _x_m_l_http_request. Splitting into words first (acronym runs, capitalised words, lowercase runs, digit runs) and then joining fixes both directions and also handles kebab-case. Leading underscores carry meaning (_id, __typename) and are kept. A WeakMap makes cycles and shared objects convert once. If two keys collide after conversion (userId and user_id), the strong answer throws rather than silently losing one. Note the round trip isn't exact: userID comes back as userId.
// Split any key into words: snake_case, kebab-case, camelCase, PascalCase, acronyms and digits.// "XMLHttpRequest" -> xml http request "userID" -> user id "version2Beta" -> version 2 betafunction words(key) {return key.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g) ?? [];}// Leading underscores mark private or special keys (_id, __typename): keep them as they are.function convert(key, join) {const lead = /^_*/.exec(key)[0];const parts = words(key.slice(lead.length));return parts.length ? lead + join(parts.map((w) => w.toLowerCase())) : key;}const toSnake = (key) => convert(key, (ws) => ws.join('_'));const toCamel = (key) => convert(key, ([first, ...rest]) => first + rest.map((w) => w[0].toUpperCase() + w.slice(1)).join(''));const isPlainObject = (v) => {if (v === null || typeof v !== 'object') return false;const proto = Object.getPrototypeOf(v);return proto === Object.prototype || proto === null;};function convertKeysDeep(value, fn, seen = new WeakMap()) {if (Array.isArray(value)) return value.map((item) => convertKeysDeep(item, fn, seen));if (!isPlainObject(value)) return value;if (seen.has(value)) return seen.get(value); // a cycle or a shared object converts onceconst out = {};seen.set(value, out);for (const [key, inner] of Object.entries(value)) {const next = fn(key);// Two keys that collide ("userId" and "user_id") would silently overwrite each other.if (Object.prototype.hasOwnProperty.call(out, next)) throw new Error(`keys collide on "${next}"`);out[next] = convertKeysDeep(inner, fn, seen);}return out;}const keysToCamel = (value) => convertKeysDeep(value, toCamel);const keysToSnake = (value) => convertKeysDeep(value, toSnake);
passes 6 checks run on every build, against the native method where there is one
- acronyms and digits split into sensible words
- leading underscores are kept
- already-converted keys stay the same
- colliding keys throw instead of overwriting
- cycles and shared objects convert once
- the round trip is not always exact
A snake_case API in a camelCase app
Python and Ruby backends usually return created_at, user_id. Converting once at the edge (a fetch wrapper or an axios response interceptor) keeps the whole frontend camelCase and converts back on the way out.
Why only plain objects
A FormData, a Blob or a Date in a request body must reach the network unchanged; converting their "keys" breaks them. Checking the prototype is how libraries tell a record from a value.
GraphQL's double underscores
GraphQL responses carry __typename, which client caches rely on. A converter that turns it into typename breaks normalised caching; that's why leading underscores are kept.
Converting only the top level, so nested objects from the API stay snake_case.
Recursing into every object, which mangles
Date,Mapor class instances.Mutating the input with
delete obj[key]: other code holding that object sees it change.userIDbecominguser_i_dbecause each capital is treated as its own word.Two keys that collide after conversion silently overwrite each other.
How would you type this in TypeScript?
With template literal types: type CamelCase<S> = S extends${infer H}_${infer T}?${H}${Capitalize<CamelCase<T>>}: S, and a mapped type over the keys ({ [K in keyof T as CamelCase<K & string>]: ... }), recursing into nested objects.
Where should this conversion live?
At one boundary: the HTTP client. Doing it ad hoc in components means some data is converted and some isn't, which is how user.userId and user.user_id end up in the same codebase.
What about query strings?
Convert the keys before building URLSearchParams; the values are user data and must not be touched.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap