invert()
invert<
T>(object):Record<T[keyofT], keyofT>
Creates a new object by swapping keys and values.
last key wins.
Type Parametersโ
T: T extends Record<PropertyKey, PropertyKey>โ
The type of the input object.
Parametersโ
object: Tโ
The object to invert.
Returns: Record<T[keyof T], keyof T>โ
A new object with keys and values swapped.
Sinceโ
2.0.0
Noteโ
Only enumerable string keys are included (Symbol keys are ignored).
Performanceโ
O(n) time & space.
Also known asโ
invert (Lodash, es-toolkit, Remeda, Radashi) ยท invertObj (Ramda) ยท โ (Effect, Modern Dash, Antfu)
Exampleโ
invert({ a: 1, b: 2, c: 3 });
// => { 1: 'a', 2: 'b', 3: 'c' }
invert({ a: 1, b: 1, c: 2 });
// => { 1: 'b', 2: 'c' }
const statusCodes = { success: 200, notFound: 404 };
const codeToStatus = invert(statusCodes);
codeToStatus[200]; // => 'success'
How it works?โ
Creates a new object by swapping keys and values.
Key-Value Swapโ
Duplicate Valuesโ
When values are duplicated, the last key wins:
Use Case: Lookup Tableโ
Use Casesโ
Build reverse enum lookups ๐โ
Create a reverse mapping from enum-like objects for bidirectional access. Essential for converting between display names and internal codes.
const StatusCode = { PENDING: 'P', APPROVED: 'A', REJECTED: 'R' };
const StatusLabel = invert(StatusCode);
// { 'P': 'PENDING', 'A': 'APPROVED', 'R': 'REJECTED' }
const label = StatusLabel[record.status]; // 'P' โ 'PENDING'
Swap keys and valuesโ
Create a reverse lookup map from an object. Useful for bidirectional mapping (e.g., ID to Name and Name to ID).
const idMap = { admin: 1, user: 2 };
const roleMap = invert(idMap); // { '1': 'admin', '2': 'user' }
Index by valueโ
Quickly find the key associated with a specific value.
const colors = { red: '#ff0000', blue: '#0000ff' };
const colorName = invert(colors)['#ff0000']; // 'red'