I have an extremely large JSON object structured like this:
{A : 1, B : 2, C : 3, D : 4}
I need a function that can swap the values with keys in my object and I don't know how to do it. I would need an output like this:
{1 : A, 2 : B, 3 : C, 4 : D}
Is there any way that I can do this would manually created a new object where everything is swapped?
Thanks
Get the keys of the object, and then use the Array's reduce function to go through each key and set the value as the key, and the key as the value.
Example here FIDDLE don't forget to turn on your console to see the results.
Using ES6:
you can use lodash function _.invert it also can use multivlaue
In ES6/ES2015 you can combine use of Object.keys and reduce with the new Object.assign function, an arrow function, and a computed property name for a pretty straightforward single statement solution.
If you're transpiling using the object spread operator (stage 3 as of writing this) that will simplify things a bit further.
Finally, if you have Object.entries available (stage 4 as of writing), you can clean up the logic a touch more (IMO).
As a complement of @joslarson and @jPO answers:
Without ES6 needed, you can use
Object.keys
Array.reduce
and the Comma Operator:Some may find it ugly, but it's "kinda" quicker as the
reduce
doesn't spread all the properties of theobj
on each loop.