Skip to content

Instantly share code, notes, and snippets.

@joker314
Created November 1, 2018 13:48
Show Gist options
  • Save joker314/384acf46bc324fba52cd527a75f663a9 to your computer and use it in GitHub Desktop.
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"}
/**
* 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