Javascript Icon Get 62% off the JavaScript Master bundle

See the bundle then add to cart and your discount is applied.

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]]
Object
  .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']]
Object
  .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' }
Object
  .fromEntries(flipped);

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(
  Object
    .entries(data)
    .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.

Learn JavaScript the right way.

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students.

Todd Motto

with Todd Motto

Google Developer Expert icon Google Developer Expert

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover