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'