Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active January 28, 2023 07:46
Show Gist options
  • Save yano3nora/3e72e501788049145b40b0f6132532d4 to your computer and use it in GitHub Desktop.
Save yano3nora/3e72e501788049145b40b0f6132532d4 to your computer and use it in GitHub Desktop.
[js: Swap (invert) object's keys and values] #js
/**
* @link https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
* @example
* const swapped = objectSwap({ x: 1, y: 2 }) // { 1: 'x', 2: 'y' }
* ^^^^^^^ infer Record<1 | 2, 'x' | 'y'>
*/
export const objectSwap = <
T extends PropertyKey,
U extends PropertyKey,
>(object: Record<T, U>) => Object.fromEntries(
Object.entries(object).map(([key, value]) => [
value,
key,
]),
) as Record<U, T>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment