renameKeys
Renames keys of an object based on a mapping. Keys not present in the mapping are preserved as-is.
1/**
2 * Renames keys of an object based on a mapping.
3 * Keys not present in the mapping are preserved as-is.
4 *
5 * @param obj - The original object.
6 * @param keyMap - An object defining the old-to-new key mapping.
7 * @returns A new object with renamed keys.
8 */
9export function renameKeys(
10 obj: Record<string, any>,
11 keyMap: Record<string, string>
12): Record<string, any> {
13 return Object.fromEntries(
14 Object.entries(obj).map(([key, value]) => [keyMap[key] ?? key, value])
15 );
16}
Clean and Concise Implementation
Uses
Object.entries
andObject.fromEntries
for an elegant and expressive one-liner transformation.Non-Destructive Behavior
Preserves keys not listed in the mapping, making the operation safe and non-invasive.
Highly Flexible
Works with any string-based key mapping, allowing for arbitrary renaming strategies.
Pure and Predictable
Returns a new object without modifying the original, supporting immutable data patterns.
Tests | Examples
1test('renameKeys - renames matching keys', () => {
2 const obj = { a: 1, b: 2, c: 3 };
3 const map = { a: 'x', b: 'y' };
4 expect(renameKeys(obj, map)).toEqual({ x: 1, y: 2, c: 3 });
5});
6
7test('renameKeys - empty key map returns original keys', () => {
8 const obj = { foo: 42 };
9 expect(renameKeys(obj, {})).toEqual({ foo: 42 });
10});
11
12test('renameKeys - empty object returns empty object', () => {
13 const map = { a: 'x' };
14 expect(renameKeys({}, map)).toEqual({});
15});
16
17test('renameKeys - key not in map stays the same', () => {
18 const obj = { hello: 'world' };
19 const map = { foo: 'bar' };
20 expect(renameKeys(obj, map)).toEqual({ hello: 'world' });
21});
22
23test('renameKeys - works with nested keys (flat only)', () => {
24 const obj = { a: 1, 'b.c': 2 };
25 const map = { 'b.c': 'd.e' };
26 expect(renameKeys(obj, map)).toEqual({ a: 1, 'd.e': 2 });
27});
Common Use Cases
Data Transformation for APIs
Rename internal field names to match external API contract formats (e.g.,
firstName
→first_name
).UI Layer Adaptation
Map backend or raw data fields to UI-friendly or user-readable labels.
Import/Export Utilities
Adjust keys when converting between data formats (e.g., CSV headers, Excel columns).
Migration Scripts
Rename fields during schema migrations or when aligning legacy data with new models.
Normalization of Third-Party Data
Clean and rename keys from external systems before integrating them into your own data model.