Use Object.entries() with reduce or fromEntries to transform keys
const obj = { first_name: 'John', last_name: 'Doe' };
const camelObj = Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k.replace(/_([a-z])/g, (_, c) => c.toUpperCase()), v]
)
);
console.log(camelObj); // { firstName: 'John', lastName: 'Doe' }const snakeObj = {
user_name: 'alice',
email_address: '[email protected]',
is_verified: true
};
// Convert to camelCase
const toCamelKeys = obj =>
Object.fromEntries(
Object.entries(obj).map(([key, val]) => [
key.replace(/_([a-z])/g, (_, c) => c.toUpperCase()),
val
])
);
console.log(toCamelKeys(snakeObj));
// Prefix all keys
const prefixKeys = (obj, prefix) =>
Object.fromEntries(
Object.entries(obj).map(([k, v]) => [`${prefix}${k}`, v])
);
console.log(prefixKeys({ id: 1, name: 'Test' }, 'user_'));function deepTransform(obj, transform) {
if (typeof obj !== 'object') return obj;
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [
transform(k),
deepTransform(v, transform)
])
);
}const rename = (obj, map) =>
Object.fromEntries(
Object.entries(obj).map(([k, v]) => [map[k] || k, v])
);Avoid mutating original object
// DON'T DO THIS
for (var key in obj) {
var newKey = transform(key);
obj[newKey] = obj[key];
delete obj[key];
}✓ Works in all modern browsers (ES2019+)