Skip to main content

invert()

invert<T>(object): Record<T[keyof T], keyof T>

Creates a new object by swapping keys and values.

DUPLICATE 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);
});