mapKeys()
mapKeys<
T,K>(object,transform):Record<K,T[keyofT]>
Creates a new object with keys transformed by a function.
Does not mutate original. Duplicate transformed keys: last value wins.
Type Parametersβ
T: T extends Record<PropertyKey, any>β
The type of the input object.
K: K extends PropertyKeyβ
The type of the transformed keys.
Parametersβ
object: Tβ
The object to iterate over.
transform: (value, key, object) => Kβ
Function to generate new keys: (value, key, object) => newKey.
Returns: Record<K, T[keyof T]>β
A new object with transformed keys and original values.
Sinceβ
2.0.0
Noteβ
Only enumerable string keys are included (Symbol keys are ignored).
Performanceβ
O(n) time & space.
Also known asβ
mapKeys (Lodash, es-toolkit, Remeda, Radashi) Β· objectMap (Antfu) Β· β (Ramda, Effect, Modern Dash)
Exampleβ
const obj = { a: 1, b: 2 };
mapKeys(obj, (_, key) => key.toUpperCase());
// => { A: 1, B: 2 }
mapKeys(obj, (value, key) => `${key}_${value}`);
// => { a_1: 1, b_2: 2 }
// snake_case to camelCase
mapKeys({ first_name: 'John' }, (_, key) =>
key.replace(/_([a-z])/g, (_, l) => l.toUpperCase())
);
// => { firstName: 'John' }
How it works?β
Creates a new object with keys transformed by a function.
Transformation Flowβ
snake_case to camelCaseβ
Use Casesβ
Rename object keys πβ
Transform all keys of an object using a function. Useful for standardizing casing (e.g., snake_case to camelCase).
const camelCased = mapKeys(snakeObj, (_, key) => toCamelCase(key));
Normalize HTTP headersβ
Convert all header names to lowercase for consistent case-insensitive lookup.
const headers = { 'Content-Type': 'json', 'X-Auth': 'token' };
const normalized = mapKeys(headers, (_, k) => k.toLowerCase());
// { 'content-type': 'json', 'x-auth': 'token' }
Prefix keysβ
Add a namespace prefix to all keys in an object. Useful for merging data into flat structures like environment variables.
const env = mapKeys(config, (_, key) => `APP_${key.toUpperCase()}`);
// { APP_HOST: 'localhost', APP_PORT: 3000 }
Convert API response keys for frontend consumptionβ
Transform snake_case API response keys to camelCase for frontend use. Essential for any app consuming REST APIs with different naming conventions.
const apiResponse = { user_name: "Alice", created_at: "2025-01-15", is_active: true };
const frontendData = mapKeys(apiResponse, (_, key) => camelCase(key));
// => { userName: "Alice", createdAt: "2025-01-15", isActive: true }
Namespace CSS custom properties from design tokensβ
Prefix design token keys to generate CSS custom property names. Perfect for design system build tools generating CSS variables.
const tokens = { primary: "#3b82f6", secondary: "#6b7280", spacing: "16px" };
const cssVars = mapKeys(tokens, (_, key) => `--ds-${kebabCase(key)}`);
// => { "--ds-primary": "#3b82f6", "--ds-secondary": "#6b7280", "--ds-spacing": "16px" }
// Apply to root element
Object.entries(cssVars).forEach(([prop, value]) => {
document.documentElement.style.setProperty(prop, value);
});