Created
November 1, 2018 13:48
-
-
Save joker314/384acf46bc324fba52cd527a75f663a9 to your computer and use it in GitHub Desktop.
A function to reverse an object. For example, {a: "b", c: "d"} would become {b: "a", d: "c"}
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
/** | |
* A function to swap keys with values | |
* in a JavaScript object. | |
* | |
* {a: 'b', c: 'd'} => {b: 'a', d: 'c'} | |
*/ | |
function reverseObject(obj) { | |
const reducer = (accumulator, [key, value]) => Object.assign(accumulator, {[value]: key}) | |
return Object.entries(obj).reduce(reducer, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment