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'
Map keyboard shortcuts to actionsβ
Create a reverse lookup from key combinations to action names. Essential for keyboard shortcut systems and accessibility features.
const actionToKey = {
save: "Ctrl+S",
undo: "Ctrl+Z",
redo: "Ctrl+Shift+Z",
search: "Ctrl+K",
close: "Escape",
};
const keyToAction = invert(actionToKey);
// => { "Ctrl+S": "save", "Ctrl+Z": "undo", ... }
document.addEventListener("keydown", (e) => {
const combo = formatKeyCombo(e);
const action = keyToAction[combo];
if (action) executeAction(action);
});