Last active
January 28, 2023 07:46
-
-
Save yano3nora/3e72e501788049145b40b0f6132532d4 to your computer and use it in GitHub Desktop.
[js: Swap (invert) object's keys and values] #js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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