Aller au contenu principal

mapKeys()

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

Creates a new object with keys transformed by a function.

remarque

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 }