Skip to main content

mapKeys()

mapKeys<T, K>(object, transform): Record<K, T[keyof T]>

Creates a new object with keys transformed by a function.

note

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 }