JavaScript object-key guide
Convert Object Keys to snake_case in JavaScript
When a frontend uses camelCase but an API expects snake_case, transform object keys at the serialization boundary instead of rebuilding every payload.
JavaScript implementation
function toSnakeKey(key) {
return key.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase()
}
function keysToSnake(value) {
if (Array.isArray(value)) return value.map(keysToSnake)
if (value === null || typeof value !== "object") return value
const output = {}
for (const [key, child] of Object.entries(value)) {
const nextKey = toSnakeKey(key)
if (Object.hasOwn(output, nextKey)) throw new Error(`Key collision: ${nextKey}`)
output[nextKey] = keysToSnake(child)
}
return output
}Split ordinary camelCase and acronym boundaries before normalizing separators and lowercasing the final key.
Rebuild objects instead of mutating the input so collision checks can happen before assigning values.
Production edge cases
- Project acronyms may need explicit mapping rules.
- Semantic prefixes such as _id and $schema may need to stay intact.
- Decide whether the API contract needs deep or top-level-only conversion.
- Use collision checks because different JavaScript keys can normalize to the same snake_case output.
Test object keys online
Paste a JSON object to test recursive key conversion, top-level-only mode, excluded keys, underscore/dollar prefixes, and collision handling before you copy the logic into an application.
Drop a .json file here or choose one from your device
Files are read only in your browser. Maximum file size: 5 MB.
{
"user_profile": {
"first_name": "Ada",
"created_at": "2026-09-12"
}
}Parsing, file reading, formatting, and key conversion run locally in your browser. JSON input is not sent to a conversion server.