invert
Inverts keys and values in an object. If multiple keys share the same value, the last one will overwrite the previous.
1/**
2 * Inverts keys and values in an object.
3 * If multiple keys share the same value, the last one will overwrite the previous.
4 *
5 * @param obj - The object to invert. Values must be string or number.
6 * @returns A new object with values as keys and keys as values.
7 */
8export function invert(obj: Record<string, string | number>): Record<string | number, string> {
9 const result: Record<string | number, string> = {};
10 for (const key in obj) {
11 result[obj[key]] = key;
12 }
13 return result;
14}
Simple Key–Value Reversal
Transforms an object by flipping keys and values, which is especially useful for reverse lookups.
Compact and Efficient
Uses a straightforward loop with minimal overhead, ensuring fast performance even on large objects.
Supports Both Strings and Numbers
Accepts values as either
string
ornumber
, covering the most common cases for keys.Clear Overwrite Behavior
Last-value-wins approach for duplicate values ensures predictable and deterministic results.
Tests | Examples
1test('invert - basic key-value inversion', () => {
2 const input = { a: 'x', b: 'y' };
3 const expected = { x: 'a', y: 'b' };
4 expect(invert(input)).toEqual(expected);
5});
6
7test('invert - numeric values as keys', () => {
8 const input = { one: 1, two: 2 };
9 const expected = { 1: 'one', 2: 'two' };
10 expect(invert(input)).toEqual(expected);
11});
12
13test('invert - same value for multiple keys (last wins)', () => {
14 const input = { a: 'x', b: 'x', c: 'y' };
15 const expected = { x: 'b', y: 'c' };
16 expect(invert(input)).toEqual(expected);
17});
18
19test('invert - empty object', () => {
20 expect(invert({})).toEqual({});
21});
Common Use Cases
Reverse Lookup Tables
Quickly find the original key by value, such as retrieving status codes, enum labels, or ID-to-name maps.
Data Normalization
Flip role-to-ID or label-to-value mappings for compatibility with different systems.
UI Label Mapping
Translate UI display values back to internal keys for forms, filters, or analytics.
Localization or Translation Tables
Swap keys and values to build quick reverse dictionaries for UI text or translations.
Testing and Debugging
Easily inspect reverse mappings when validating bidirectional or symmetric data structures.