💲 Black Friday Special

Get an extra 35% OFF everything with coupon code BLACK_FRIDAY

0 days
00 hours
00 mins
00 secs

Write JavaScript like a pro. Javascript Icon

Follow the ultimate JavaScript roadmap.

Reverse Object Keys and Values in JavaScript

Easily reverse your object keys and values using the lesser-known but powerful Object.entries and Object.fromEntries.

I recently ran into a data structure that I needed to flip, or invert/reverse.

Let’s assume the data looked like this:

{ x: 1, y: 2 }

We want to invert the object keys and values to end up with this:

{ 1: 'x', 2: 'y' }

Pro tip: JavaScript stores ‘numbers’ as strings when used as key values - even though they may look like numbers.

So how do we reverse this data structure?

Let’s first convert the keys and values to an array, so we can swap their order.

For this, I’ll use Object.entries():

// [['x', 1], ['y', 2]]
  .entries({ x: 1, y: 2 });

As this returns a new array, we can map over the values and swap them out using a new array and a little destructuring:

// [[1, 'x'], [2, 'y']]
  .entries({ x: 1, y: 2 })
  .map(([key, value]) => [value, key]);

Now time to bring it all back together into a plain JavaScript object.

We’ll take our multidimensional array and pass it into Object.fromEntries(), which as the name describes expects data in an “entries” format:

const flipped = Object
  .entries({ x: 1, y: 2 })
  .map(([key, value]) => [value, key]);

// { 1: 'x', 2: 'y' }

That’s it!

However, as with all good code, we should totally wrap it inside a utility function for maximum reuse and testability:

const flip = (data) => Object.fromEntries(
    .map(([key, value]) => [value, key])

// { 1: 'x', 2: 'y' }
flip({ x: 1, y: 2 });

🏆 P.S. check out my latest JavaScript courses if you’re serious about taking your skills to the top.

There you have it, enjoy and happy flipping.

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover