Back to Home
Objects

How to Transform Object Keys

Use Object.entries() with reduce or fromEntries to transform keys

Quick Answer (2024 ES6+ Way)

javascript
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' }

Live Example

javascript
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_'));

Common Variations

Deep Key Transform
javascript
function deepTransform(obj, transform) {
  if (typeof obj !== 'object') return obj;
  return Object.fromEntries(
    Object.entries(obj).map(([k, v]) => [
      transform(k),
      deepTransform(v, transform)
    ])
  );
}
Rename Specific Keys
javascript
const rename = (obj, map) =>
  Object.fromEntries(
    Object.entries(obj).map(([k, v]) => [map[k] || k, v])
  );

❌ Don't Do This (Outdated Way)

Avoid mutating original object

javascript
// DON'T DO THIS
for (var key in obj) {
  var newKey = transform(key);
  obj[newKey] = obj[key];
  delete obj[key];
}

Browser Support

Works in all modern browsers (ES2019+)

#objects#keys#transform